After using spring.net in ASP.NET for long, I was looking for a simple, fast and no XML Dependency Injector. For an ASP.NET MVC4 application, I finally settled on Ninject because of its no XML approach, simplicity and ease of use.
So, how to choose a Dependency Injector? Well, every Dependency Injector has its strengths and weaknesses and comes with a different feature set. Choosing Dependency Injector is a matter of evaluation and what you expect out of it.
Ninject is an open source Dependency Injector for .NET, created by Nate Kohari, and it comes with a good set of extension and one of them is extension for ASP.NET MVC3.
Anyways, like me, if you also like to try new and promising stuff, you will like to use Ninject , you can read more about Ninject on Ninject.org.
Why Dependency Injection?
There are several benefits of using dependency injection rather than having components satisfy their own dependencies. Some of these benefits are:
- Reduced boiler plate code and dependency carrying, flexibility to use alternative implementation of a given service without recompiling the application code
- Loose coupling between classes by promoting use of interfaces
- Code becomes more reusable, testable and readable. If you are new to DI, you can read more.
What Do We Need to Integrate Ninject in ASP.NET MVC4?
Download Ninject and its ASP.NET MVC3 extension (there is no extension for ASP.NET MVC4 yet).
How to Integrate Ninject in ASP.NET MVC4?
- Add Ninject Dependencies to the project. You need to add reference to following DLLs in your ASP.NET MVC4 project
- Modify controller code to declare a read-only member variable of your service and modify the constructor to introduce the service instance parameter as below:
10. public class HomeController : Controller
12. private readonly IMessageService _messageService;
13. public HomeController(IMessageService messageService)
15. _messageService = messageService;
18. public ActionResult Index()
20. ViewBag.Message = _messageService.GetWelcomeMessage();
21. return View();
IMesssageService interface and want to
inject _messageService with the implementation
MessageService using Ninject.
8. public class MessageService:IMessageService
10. public string GetWelcomeMessage()
12. return "Welcome to Ninject MVC4 Example";
- Modify Global.asax, inherit
MvcApplication class from
NinjectHttpApplication which is part of
CreateKernel method as follows: Create instance of
StandardKernel, Load Executing assembly using the kernel, Bind Service Interface with the implementation to be injected.
- In this example, while constructing the controllers, this will inject the
MessageService instance inside
HomeController’s constructor so that it can be assigned to
_messageService member variable.
16. public class MvcApplication : NinjectHttpApplication
18. protected override IKernel CreateKernel()
20. var kernel = new StandardKernel();
23. return kernel;
25. protected override void OnApplicationStarted()
OnApplicationStarted to Register Filters, routes and bundles, etc. (standard ASP.NET MVC4 stuff which we used to do in
Application_Start event when not using ninject)
Cool, you are done, let's run the application and see that welcome message is now coming from the
MessageService, which got injected into the
Ninject is now integrated withASp.NET MVC4, no different than the approach used to integrate it with ASP.NET MVC3.
If you want to integrate it with ASP.NET webapi, (injecting into apicontrollers) using DependencyResolver approach, just implement
System.Web.Http.Dependencies.IDependencyResolver on your own.
Why? Because currently Ninject’s Dependency Resolver comes with implementation of
System.Web.Mvc.IDependencyResolver which cannot be assigned to
GlobalConfiguration.Configuration of WebApi Application, it expects an instance of
System.Web.Http.Dependencies.IDependencyResolver instead of
System.Web.Mvc.IDependencyResolver, read more about this.
86. public class LocalNinjectDependencyResolver :
88. private readonly IKernel _kernel;
90. public LocalNinjectDependencyResolver(IKernel kernel)
92. _kernel = kernel;
94. public System.Web.Http.Dependencies.IDependencyScope BeginScope()
96. return this;
99. public object GetService(Type serviceType)
101. return _kernel.TryGet(serviceType);
104. public IEnumerable<object> GetServices(Type serviceType)
108. return _kernel.GetAll(serviceType);
110. catch (Exception)
112. return new List<object>();
116. public void Dispose()
And modify the
CreateKernel method as below to assign an instance of
protected override IKernel CreateKernel()
47. var kernel = new StandardKernel();
49. GlobalConfiguration.Configuration.DependencyResolver =
50. return kernel;
That’s it, we can live with this workaround for now. Please click here if you need to download the sample source code.