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

前端 未结 17 1540
猫巷女王i
猫巷女王i 2020-11-30 01:41

UPDATE - Please look at my answer for a link and explanation of the solution to this problem

Before we start, I know this is a very common quest

17条回答
  •  难免孤独
    2020-11-30 02:29

    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.

提交回复
热议问题