-
Notifications
You must be signed in to change notification settings - Fork 85
Dependency injection for controllers
Mikhail edited this page Oct 18, 2018
·
4 revisions
In the previous step we already prepared anything that is necessary for controller injection. The constructor of controllers can be changed now to accept dependencies. The only thing that has to be done is to configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding. Of course, you can still add a binding for the controller in case you need to specify more information for the binding (e.g. an additional constructor argument).
Here is an example of a controller that has the welcome message service as dependency.
public class HomeController : Controller
{
private readonly IWelcomeMessageService welcomeMessageService;
public HomeController(IWelcomeMessageService welcomeMessageService)
{
this.welcomeMessageService = welcomeMessageService;
}
public void Index()
{
ViewModel.Message = this.welcomeMessageService.TodaysWelcomeMessage;
return View();
}
}
public class WelcomeMessageServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<IWelcomeMessageService>().To<WelcomeMessageService>();
}
}