Step 1
Create a NinjectControllerFactory
This class derives from DefaultControllerFactory class.
Create a NinjectControllerFactory
- public class NinjectControllerFactory: DefaultControllerFactory {
- private IKernel ninjectKernel;
- public NinjectControllerFactory() {
- ninjectKernel = new StandardKernel();
- AddBindings();
- }
- protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {
- return controllerType == null ? null : (IController) ninjectKernel.Get(controllerType);
- }
- private void AddBindings() {
- ninjectKernel.Bind < IAccountService > ().To < AccountService > ();
- // add your bindings here as required
- }
The main method that you have to keep in mind here is the "AddBindings" private method. Basically, this is where you will bind your interface's implementations that you want to inject. You will add bindings for each of your services that you would like to be available to your controllers from here.
Step 2
Register NinjectFactory in Global.asax
Register NinjectFactory in Global.asax
- ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
Now you can inject the services in your controller class like this:
- public AccountController(
- IFormsAuthService _formsService,
- IAccountService _accountService,
- IEmailService _emailService,
- IUserActivityService userActivityService)
- {
Joseph HenimeXPosted Feb 17, 2021, 11:15 AM
PM> Install-Package Microsoft.AspNet.Mvc -Version 5.2.3
Joseph HenimeXPosted Feb 17, 2021, 8:57 AM
Private IKernel _kernel; public NinjectControllerFactory(INinjectModule module) { _kernel = new StandardKernel(module); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController) _kernel.Get(controllerType); }
Joseph HenimeXPosted Feb 17, 2021, 8:53 AM
NinjectControllerFactory.GetControllerInstance (RequestContext, Type) no suitable method found to override
Akhilesh TripathiPosted Sep 7, 2017, 5:30 AM
Very nice and useful information.