Tuesday, August 6, 2013

Enterprise Library 6: InvalidOperationException - 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

Last week I finally had some time to have a look at Enterprise Library version 6. The Microsoft Patterns and Practices team decided to remove the dependency on Unity, so creating an EntLib object should be done using one of the available factory classes.
In this case I tried to created an instance of a Database object:
Database db = DatabaseFactory.CreateDatabase("Northwind");
Life is never so simple, so it failed with the following exception 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.”
With Enterprise Library 6 we first have to specify how the application block should load it configuration information. For the Database Application Block you can use the SetDatabaseProviderFactory method:
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
Probably even better is to avoid the static DatabaseFactory at all and use the DatabaseProviderFactory class directly:
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("Northwind");

5 comments:

Anonymous said...

Without using the static keyword before the constructor, this code works really fine. Thanks a lot dude.

Junq Bond said...

Thanks! This cut right to the chase. Very helpful post.

Anonymous said...

I am generating this same error. I first added it to a DAL class, compiled, then it said the databasefactory is already set. So after commenting it out, it returns orgininal error. So where in the code do I add this? I do not want to repeat it in every DAL class, do I add it in the app.config application block? WHERE DO I ADD IT?

Anonymous said...

Same question.... Where does this code go?

Anonymous said...

Thanks, really useful.