Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Base Controller and Ninject

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
    { ... }
like image 319
scottrakes Avatar asked Nov 27 '10 14:11

scottrakes


People also ask

What is ninject used for?

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.

How does MVC know which controller to use?

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.

What is Injection in MVC?

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).


1 Answers

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; }


}
like image 182
dotjoe Avatar answered Oct 23 '22 05:10

dotjoe