I needed to create a simple application block for Enterprise Library using the new Application Block Software Factory for a presentation. Given that I just created an Enterprise Library Plug-In for the RepositoryFactory:

I realized I had the makings of a simple Dependency Injection Application Block. Very simple. Actually, more of a glorified Factory Method that has potential :)
As it turns out, it dawned on me that the RepositoryFactory Class in the Repository Factory is not constrained to just creating Repository Classes generated by the software factory, but will essentially create any type with a default constructor. The following:
ICustomerRepository repository = RepositoryFactory.Create<ICustomerRepository>();
could just as well be:
IProductCatalog catalog = RepositoryFactory.Create<IProductCatalog>();
In fact in retrospect, perhaps the class could/should have been called ObjectFactory and placed into a separate assembly.
Basically, this is what I was aiming for in the Dependency Injection Application Block. An ObjectFactory that created objects with simple default constructors similar to the RepositoryFactory Class. Again, this is an example for a presentation.
So, that is basically what I did. The GUI Designer is pretty much the same as what I created before except with a few name changes:

I thought I might be able to use code from the RepositoryFactory Class, but the design was not appropriate for my needs. I wanted more functionality and ended up with a starter API like:
ObjectFactory.Initialize();
ObjectFactory.Initialize(IConfigurationSource configurationSource);
ObjectFactory.Create<T>();
ObjectFactory.Add<TInterface,TConcrete>();
ObjectFactory.Remove<T>();
ObjectFactory.Clear();
Here is a quick console application I created just for play:

Here is some code that I was playing with to show the use of the Dependency Injection Application Block:
// Get From App.config
ObjectFactory.Initialize();
ObjectFactory.Clear();
// Get From DI.config
ObjectFactory.Initialize(new FileConfigurationSource("../../DI.config"));
// Add ProductCatalog Manually
ObjectFactory.Add<IProductCatalog,ProductCatalog>();
// Get Product
IProductRepository repository = ObjectFactory.Create<IProductRepository>();
Product product = repository.GetProductByProductId(1);
// Get Category
ICategoryRepository repository2 = ObjectFactory.Create<ICategoryRepository>();
Category category = repository2.GetCategoryByCategoryId(3);
// Remove CategoryRepository
ObjectFactory.Remove<ICategoryRepository>();
ObjectFactory.Clear();
Pretty basic, but not a bad example that ties in not only the RepositoryFactory but mimics some basic features found in both the Smart Client and Web Client Software Factory.
If you are interested more in the RepositoryFactory Class, you can watch the screencasts:
Posted
09-16-2007 1:56 PM
by
David Hayden