I'm using MVC 5.2.3 and I have included packages
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