In this post I will write about how one can quickly get started with Ninject Dependency Injection framework in your ASP.NET MVC application.
Step 1
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 > ();
-
- }
This class derives from DefaultControllerFactory class.
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
- ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
That's it!
Now you can inject the services in your controller class like this:
- public AccountController(
- IFormsAuthService _formsService,
- IAccountService _accountService,
- IEmailService _emailService,
- IUserActivityService userActivityService)
- {
I hope you found this post useful.