Search code examples
c#asp.net-mvcasp.net-mvc-5ninject

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?


Solution

  • 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