Creating Dependency Injection with ASP.NET Core is fairly easy. The documentation explains it very well here and this guy has a killer video to explain it.
However, I want to do the same thing with my ASP.NET MVC 5 project. How can handle dependency injection with ASP.MVC 5?
Also, is Dependency injection limited to controllers only or can it work with any class?
For this answer I downloaded a Microsoft Example of WebApi project as a basis for the example and added DI services to it as follows,
After the standard MapHttpRoute configuration, add code to register which services you need
I then amended the existing controller to take the DI type (note there is just the one ctor)
My Default Dependency Resolver
I recommend you use Autofac, there are anothers fwk like unity, ninject, the benchmarks autofac has excelent perfomance.
http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-comparison
Here is the integration with MVC (and works with all class)
http://docs.autofac.org/en/latest/integration/mvc.html
The simplest way to implements Dependency Injection in ASP.NET MVC 5 is to use the tool developed by Microsoft itself, called
Unity
.You can find many resources on the internet about it, and you can start by reading the official documentation available here: Developer's Guide to Dependency Injection Using Unity
It works with any class, in any project, as long as you register the Interface related to the Implementation (if you want to take profit of the IoC pattern), all you have to do then is to add the Interface instantiation in your constructor.
I recommend using
Windsor
, by installing the nuget packageCastle Windsor MVC Bootstrapper
, then you can create a service that implementsIWindsorInstaller
, something like this:Then inside your controller something like this:
And by default the library will handle sending the right service to your controller by calling the
install()
ofServiceRegister
at start up because it implementsIWindsorInstaller
In this video a Microsoft MVP demos dependency injection in MVC5 with AutoFac. Very clear explanation on how to set it up:
Dependency Injection MVC5 Demo
Source code is available on GitHub