Using Unity with Data App Block

Topics: Data Access Application Block
Mar 18, 2014 at 12:15 PM

I have started using Unity (DI) in my application. This also uses the Repository pattern for it's data access interface. I now want to start using the Data Application Block inside the repositories. Am I right in saying the typical implementation for this is to use constructor injections in the repository classes and pass in a Database object?

I can register the Database type in the unity container, but I wouldn't be able to use the factories would I.

Thanks for your help.

Mar 19, 2014 at 2:39 AM
Yes, typically you would use constructor injection and inject the Database instance. Database is thread-safe so you could just use a single Database class or create a new Database instance each resolve. So you could do something like this:
// Bootstrap code
// Load configuration
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());

// Register Types
IUnityContainer container = new UnityContainer();

// Instead of InjectionFactory could just register Database as singleton
container.RegisterType<Database>(new InjectionFactory( c => DatabaseFactory.CreateDatabase("MyConnection")));

Randy Levy
Enterprise Library support engineer
Support How-to
Marked as answer by gravy on 3/19/2014 at 12:15 AM
Mar 19, 2014 at 8:43 AM
This is perfect, thanks Randy.

Reading the code above (and also re-reading the entlib guide for the DAB, I have a question :)

The guide says that it is common to create an instance of the Database object and store it in an application wide variable, making it available anywhere. The code above also shows (commented out), a singleton Database instance being registered in the container.

The question, or my misunderstanding is, I was under the impression that the Database instance represented a connection to a database, and as such, should be created when needed and destroyed as soon as it was finished with. Do I have this bit wrong?


Mar 20, 2014 at 12:19 AM
The Database class is thread-safe. It doesn't maintain any instance state except for readonly connection string and provider name. There is some global state for parameter caching but that doesn't affect specific instances.

Conceptually, I wouldn't describe the Database class as representing a connection. It is more like a facade and factory to ADO.NET. Internally the Database class manages connections for you -- most methods open and then close the connection for you (the main exception being returning a reader).

Even though you can access a global Database object I would still inject it since it will give you more flexibility going forward for very little cost.

Randy Levy
Enterprise Library support engineer
Support How-to