简体   繁体   中英

MVC 5 Ninject - No parameterless constructor

I'm using MVC 5.2.3 and I have included packages

  • Ninject
  • Ninject.MVC5 (tried with MVC3 also)
  • Ninject.Web.Common
  • Ninject.Web.Common.WebHost

In NinjectWebCommon class (one that gets auto generated) I added kernel.Bind<ITestRepository>().To<TestRepository>().InRequestScope() in RegisterServices method. I then have

public class ControllerBase : Controller
    {
        protected readonly ITestRepository _testRepository;

        public ControllerBase(ITestRepository testRepository)
        {
            _testRepository = testRepository;
        }
    }

and

     public class HomeController : ControllerBase
     {
... some methods
     }

When I try to build solution I get

ControllerBase does not contain a constructor that takes 0 arguments

Even when I add parameterless constructor it just triggers that one and interface doesn't get injected.

This should work out of the box, any idea why it isn't?

Since BaseController doesn't have a parameter-less constructor, and its only constructor requires a ITestRepository argument, derived types are required to supply this argument by calling the base constructor.

Try this:

public class HomeController : ControllerBase
{
    public HomeController(ITestRepository testRepository) : base(testRepository)
    {

    }
}

This way, Ninject is able to inject ITestRepository implementation into the constructor of HomeController (the derived type) which in turn calls the base constructor (using base() ) passing the required dependency.

See MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM