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

前端 未结 17 1508
猫巷女王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:31

    The Problem seems to occur when one uses Visual Studio 2012/2013 with ASP.NET 4.0/4.5. The version of System.Web.Mvc was set to 4.0.0.0 in the Web.config file. It did not work.

    My solution was to

    1. delete NinjectWebCommon.cs
    2. copy Dere Jone's NinjectControllerFactory class into the project:

      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);
         }
      }
      
    3. change the content of Global.asax to:

      public class MvcApplication : NinjectHttpApplication
      {
         protected override IKernel CreateKernel()
         {
             IKernel kernel = new StandardKernel();
      
             // kernel.Load(Assembly.GetExecutingAssembly());
      
             // kernel.Bind().To();
      
             return kernel;
         }
      
         protected override void OnApplicationStarted()
         {
             AreaRegistration.RegisterAllAreas();
      
             WebApiConfig.Register(GlobalConfiguration.Configuration);
             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
             RouteConfig.RegisterRoutes(RouteTable.Routes);
             BundleConfig.RegisterBundles(BundleTable.Bundles);
      
             ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Kernel));
         }
      }
      

      after that your injections should work.

提交回复
热议问题