Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Using Ninject with ASP.NET MVC 2

My favorite dependency injector, Ninject, has ascended to v2! I like this framework because it's small and doesn't have a bunch of external dependencies. It does take a little extra work to get it rolling with ASP.NET MVC 2, however.

There is an extension project for MVC, and you can get that here. The core of this project, which is only a few classes, is a derivative of HttpApplication and the DefaultControllerFactory. The rub here is that the latter has a breaking change from the first version of MVC. You'll have to modify the GetControllerInstance() method of NinjectControllerFactory, because the base class from the framework now requires a RequestContext object in that method (I'm pretty sure that's to facilitate areas). The new method looks like this:

protected override IController GetControllerInstance(RequestContext requestContext, 
Type controllerType)
{
    var controller = Kernel.TryGet(controllerType) as IController;

    if (controller == null)
        return base.GetControllerInstance(requestContext, controllerType);

    var standardController = controller as Controller;

    if (standardController != null)
        standardController.ActionInvoker = CreateActionInvoker();

    return controller;
}

Rebuild the project, you're ready to rock!

EDIT (3/2/10): Nate forked the code a bit, so the project now has an MVC2 version: http://github.com/enkari/ninject.web.mvc

1 Comment

Comments have been disabled for this content.