Castle Windsor Dependency Resolver for MVC 3

The MVC3 IDependencyResolver interface has a big problem: no release method. This means that there is a potential memory leak if you are going to use it with Windsor. See my blog post about it here:

http://mikehadlow.blogspot.com/2011/02/mvc-30-idependencyresolver-interface-is.html


The interface has not changed since the beta release, so all of the implementations for various frameworks should still work. And the truth is, it's not that complicated of an interface... you should be able to roll your own without much hassle. For example, I did this one for Ninject:

public class NinjectDependencyResolver : IDependencyResolver
{
    public NinjectDependencyResolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    private readonly IKernel _kernel;

    public object GetService(Type serviceType)
    {
        return _kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _kernel.GetAll(serviceType);
    }
}

Then wire it up in global.asax like this:

    private static IKernel _kernel;
    public IKernel Kernel
    {
        get { return _kernel; }
    }

    public void Application_Start()
    {
        _kernel = new StandardKernel(new CoreInjectionModule());
        DependencyResolver.SetResolver(new NinjectDependencyResolver(Kernel));
        ...
    }

Remember, you get all kinds of goodies for free at that point, including DI for controllers, controller factories, action filters and view base classes.

EDIT: To be clear, I'm not sure what your "activators" are, but you probably don't need them. The IDependencyResolver interface handles the newing-up of controllers and views automagically.


MVCContrib is currently the authoritative source for IoC-MVC integration. Currently, the MVC3 branch only includes controller factory and IDependencyResolver implementations (and a couple other things). I recommend forking the repository and implementing the missing extension points (shouldn't be too hard), then send the team a pull request.