Powered by Blogger.

Sunday, February 23, 2014

the type initializer for threw an exception enterprise library 6

Recently while working with Enterprise Library 6, I face an error as "the type initializer for threw an exception" while creating class object.

Before checking the solution you can check out some articles like:

- Interfaces in C#.Net

- Common Language Runtime in C#.Net

- Working with enterprise library for data access in asp.net

When I digg more into it, the actual error was like below:

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements.

{System.TypeInitializationException: The type initializer for 'Class1' threw an exception. ---> System.InvalidOperationException: The static DatabaseFactory already has a database provider factory or custom methods set.
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.SetDatabases(Func`1 createDefaultDatabase, Func`2 createNamedDatabase, Boolean throwIfSet)
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.SetDatabaseProviderFactory(DatabaseProviderFactory factory, Boolean throwIfSet)
   at ...

If you are working with Enterprise library 6, then to work with data access block, then we need to write the below line within the static constructor.

static MyClass()
        DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());      

Else you will find the below error:
Database provider factory not set for the static DatabaseFactory

Actually SetDatabaseProviderFactory method takes 2 parameters, and then second parameter takes either True or False. If you set it as false then it will not thrown an exception if the factory is already set. Else it will thrown an exception if the factory is already set.

So we need to modify the line like below, so that once it sets next time it will not throw any exception.

static MyClass()
        DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(),false);