Unity Dependency Injection and Open Generic Types

Unity Dependency Injection and Open Generic Types

Author: David Hayden, Florida .NET Developer

 

I mentioned on PnPGuidance that there is a new drop of Unity:

For those of you unfamiliar with Unity, the Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection from Microsoft Patterns & Practices.

One of the new features in this recent drop of Unity is the support for open Generic Types. Hence, I can register a type of IRepository that maps to Respository like this:

 

IUnityContainer container = new UnityContainer();
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));

 

and then resolve a type of say IRepository as such from the UnityContainer:

 

IRepository<Customer> customerRepository =
    container.Resolve<IRepository<Customer>>();

 

For those of you using Castle Windsor, you can of course do the same thing. One can register the same types in a WindsorContainer:

 

IWindsorContainer container = new WindsorContainer();
container.AddComponent("Repository",typeof(IRepository<>),
typeof(Repository<>));

 

and then resolve a type of IRepository from the WindsorContainer via

 

IRepository<Customer> customerRepository =
    container.Resolve<IRepository<Customer>>();

 

For more information on Unity, you can watch my Unity IoC Screencast.

Hope this helps.

Dave

News Feed: http://www.davidhayden.com/

 

posted on Tuesday, March 25, 2008 6:27 PM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea