ASP.NET MVC 4 + Ninject MVC 3 = No parameterless constructor defined for this object

I know this is an old question but there don’t seem to be any real answers and I’ve worked around the problem so here is my solution:

Create a custom controller factory:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;
    public NinjectControllerFactory(IKernel kernel)
    {
        ninjectKernel = kernel;
    }
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (controllerType == null) ? null : (IController) ninjectKernel.Get(controllerType);
    }
}

Then, if you are using NinjectHttpApplication, add the following line to OnApplicationStarted:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Kernel));

If you aren’t using NinjectHttpApplication, then add that line somewhere after you have created your kernel and pass it a reference to your freshly created kernel.

That’s it.

Leave a Comment