Tuesday, September 29, 2009

Register and resolve generic types with Castle Windsor

If you implement repositories using a generic type T, you can use a simple resolving technic in Castle Windsor. Instead of specifying every type like:

   1: Container.Register(Component.For<IRepository<Service>>()
   2: .ImplementedBy<NHibernateRepository<Service>>());
   3: Container.Register(Component.For<IRepository<Employee>>()
   4: .ImplementedBy<NHibernateRepository<Employee>>()
   5: .LifeStyle.Transient);

But the is a more simple approach where you don´t have to specify each actual implementation, where you just tell Windsor that it is a generic type:



   1: Container.Register(
   2: Component.For(typeof (IRepository<>))
   3: .ImplementedBy(typeof (NHibernateRepository<>))
   4: .LifeStyle.Transient);

And you just saved yourself from a lot of typing. But keep in mind that people might request just anything the want, so to keep in control of what should accepted you might shield your implementation with a “…: Where T….” to encapsulate which types should be accepted.

No comments: