Setting up Inversion of Control (IoC) in ASP.NET MVC with Castle Windsor

Posted by Lirik on Stack Overflow See other posts from Stack Overflow or by Lirik
Published on 2011-02-26T01:13:35Z Indexed on 2011/02/26 7:24 UTC
Read the original article Hit count: 261

I'm going over Sanderson's Pro ASP.NET MVC Framework and in Chapter 4 he discusses Creating a Custom Controller Factory and it seems that the original method, AddComponentLifeStyle or AddComponentWithLifeStyle, used to register controllers is deprecated now:

public class WindsorControllerFactory : DefaultControllerFactory
{
    IWindsorContainer container;

    public WindsorControllerFactory()
    {
        container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

        // register all the controller types as transient
        var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                              where typeof(IController).IsAssignableFrom(t)
                              select t;

        //[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")]
        //IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class;
        foreach (Type t in controllerTypes)
        {
            container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient));
        }
    }

    // Constructs the controller instance needed to service each request
    protected override IController GetControllerInstance(Type controllerType)
    {
        return (IController)container.Resolve(controllerType);
    }
}

The new suggestion is to use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)), but I can't figure out how to present the implementing controller type in the ImplementedBy<???>() method. I tried ImplementedBy<t>() and ImplementedBy<typeof(t)>(), but I can't find the appropriate way to pass int he implementing type. Any ideas?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about reflection