Integrating MVC with Castle.Windsor

To be able to use the DI within our MVC controllers we have to replace the default MVC Framework’s Controller Factory with a custom one that uses Castle.Windsor. First of all we have to create the new Controller Factory (e.g. within a folder named “Infrastructure”):

public class CastleControllerFactory : DefaultControllerFactory
    public IWindsorContainer Container { get; private set; }
    public CastleControllerFactory(IWindsorContainer container)
        if (container != null)
            Container = container;
            throw new ArgumentNullException("container");
    protected override IController
        GetControllerInstance(RequestContext requestContext, Type controllerType)
        //Resolves Controller
        if (controllerType != null)
            return Container.Resolve(controllerType) as IController;
        return null;
    public override void ReleaseController(IController controller)
        if (controller is IDisposable)
        //Releases Controller

Now we have to tell MVC Framework to use our Controller Factory instead of the default one. To do this we have to add some code to the Application_Start() method in the global.asax file:

void Application_Start(object sender, EventArgs e)
    //Creates Castle Container
    var container = new WindsorContainer();
    container.Install(new CastleInstaller());
    //Creates Castle Controller Factory (MVC)
    var castleControllerFactory = new CastleControllerFactory(container);

The CastleInstaller class is the usual class that we use to configure the mapping between each interface and its concrete class. We can create it within the same “Infrastructure” folder in which we created the Controller Factory.

Adding all the controllers to the installer

To have Castle working with our MVC application we should remember to register all the controllers within our CastleInstaller class. To avoid this (and to not have a too long configuration) we can automatically set the configuration of all the controllers via reflection. In this way any new controller will be found and properly added to Castle without writing any explicit line of code. Here is the code:

//Register all the MVC controllers
//in the current executing assembly

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s