I am implementing Ninject dependency injection in an existing MVC 2 application that uses a base controller that all controllers inherit to set navigation and other information needed by the master page. When I set a controller to inherit from the base controller, I get the following error: "...BaseController' does not contain a constructor that takes 0 arguments. How do I get around this error? I am new to Ninject and can't figure this out.
public class BaseController : Controller
{
private INavigationRepository navigationRepository;
private ISessionService sessionService;
public BaseController(INavigationRepository navigationRepository, IMembershipService membershipService, ISessionService sessionService)
{
this.navigationRepository = navigationRepository;
this.sessionService = sessionService;
}
}
public class HomeController: BaseController
{ ... }
Why use Ninject? Ninject is a lightweight Dependency Injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glues them back together in a flexible manner.
This is because of conventions. The default convention is /{controller}/{action} , where the action is optional and defaults to Index . So when you request /Scott , MVC's routing will go and look for a controller named ScottController , all because of conventions.
The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Adding that ctor is one way
public class HomeController: BaseController
{
public HomeController(INavigationRepository navigationRepository, IMembershipService membershipService, ISessionService sessionService)
: base(navigationRepository, membershipService, sessionService) { }
}
or property injection
public class BaseController : Controller
{
[Inject]
public INavigationRepository navigationRepository { get; set; }
[Inject]
public ISessionService sessionService { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With