Castle Windsor Container Support for Generics - .NET Inversion of Control and Dependency Injection

Castle Windsor Container Support for Generics - .NET Inversion of Control and Dependency Injection

by David Hayden ( Sarasota Florida ASP.NET C# Developer )

Filed: .NET Tools

 

Ayende's new MSDN Article on Castle's Windsor Container for Inversion of Control and Dependency Injection shows off some pretty impressive support for generics in Windsor. Windsor is up to version 1.0 Release Candidate 3 and has become my container of choice. In fact, most, if not all, of the Castle Projects have made it into my toolbox.

I tested out the support for Generics using a very simple configuration.

A simplified version of the Inversion of Control Class Wrapper for the Windsor Container that was inspired by the one in Rhino Mocks.

 

public static class IoC
{
    private static IWindsorContainer _container =
        new WindsorContainer(new
XmlInterpreter("IoC.config")); public static T Resolve<T>() { return _container.Resolve<T>(); } public static T Resolve<T>(string name) { return _container.Resolve<T>(name); } }

 

A couple of classes that implement IDAO<Blog>. We have a specialized version called BlogDAO:

 

public class BlogDAO : DAO<Blog>, IDAO<Blog>
{
    public BlogDAO(IDatabase database) :
base(database) { } #region IDAO<Blog> Members public Blog FetchById(int id) { return FindOne<int>(new GetBlogByBlogId
SelectionFactory(),
new BlogFactory(),
id); }
#endregion }

 

and a generic implementation I cheated on :)

 

public class GenericDAO<T> : IDAO<T> where
T:
class, new() { public T FetchById(int id) { return new T(); } }

 

When I tell the Windsor Container that I want an implementation of IDAO<Blog>:

 

IDAO<Blog> blogDAO = IoC.Resolve<IDAO<Blog>>();

 

I can configure my Windsor Config file a couple of ways depending on if I want a specialized or generic implementation and the client code does not change:

 

<component id="BlogDAO"
               service="WebApplication1.Interfaces.IDAO`1
[[WebApplication1.Blog, WebApplication1]],
WebApplication1
" type="DataServices.BlogDAO, DataServices"/> <component id="GenericDAO" service="WebApplication1.Interfaces.IDAO`1,
WebApplication1
" type="DataServices.GenericDAO`1, DataServices"/>

 

Ayende does a great job discussing this in more detail and how the CLR represents a Generic Type, so I would read his article for a thorough discussion on the subject. Cool stuff.

Source: David Hayden ( Sarasota Florida ASP.NET C# Developer )

Filed: .NET Tools

 

posted on Sunday, November 12, 2006 12:49 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices