Powered by Blogger.

Sunday, February 23, 2014

Database provider factory not set for the static DatabaseFactory

In this post we will discuss how to resolve Microsoft enterprise library error which comes in version 6. Also you can check out some post on:

- Constraints in SQL Server 2008

- Common Language Runtime in C#.Net

- Triggers in sql server 2008

Full error message:

Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method.


If you are using Microsoft Enterprise Library 5.0 version, then while using application block you can write like below:

Database db = DatabaseFactory.CreateDatabase("ConnectionString");

But in Microsoft Enterprise Library 6 you can not write like above because, Enterprise library 6 requires to set for factory method.

SetDatabaseProviderFactory is one time setting before using application block.

So we can write like this:

DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
SqlDatabase db = DatabaseFactory.CreateDatabase("ConnectionString") as SqlDatabase;

But the problem here is, SetDatabaseProviderFactory is a one time setting, so next time when this block executes it will give an expection like below:

"The static DatabaseFactory already has a database provider factory or custom methods set"

To avoid this exception, you can write below line inside a static constructor:
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());

But the best approach according to me is instead of writting the above 2 lines, write like below:

DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("ConnectionString");

Now exception will be thrown.