In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.
**This site features an answer to the question How to explain Dependency
Injection to a 5-year old. The most highly rated answer, provided
by John Munsch provides a surprisingly accurate
analogy targeted at the (imaginary) five-year-old inquisitor:
When you go and get things out of the refrigerator for yourself,
you can cause problems. You might leave the door open, you
might get something Mommy or Daddy doesn’t want you to
have. You might even be looking for something we don’t even
have or which has expired.
What you should be doing is stating a need, “I need something
to drink with lunch,” and then we will make sure you have
something when you sit down to eat.
What this means in terms of object-oriented software development
is this: collaborating classes (the five-year-olds)
should rely on the infrastructure (the parents) to provide
** This code uses MEF to dynamically load the dll and resolve the
dependencies. ILogger dependency is resolved by MEF and injectd into
the user class. User class never receives Concrete implementation of
ILogger and it has no idea of what or which type of logger its using.**
Dependency Injection C# and ASP.NET with Unity
First why we should use depedency injection in our code ? We want to decouple other components from other classes in our program. For example we have class AnimalController which have code like this :
We look at this code and we think everything is ok but now our AnimalController is reliant on object _SantaAndHisReindeer. Automatically my Controller is bad to testing and reusability of my code will be very hard.
Very good explanation why we should use Depedency Injection and interfaces
If we want Unity to handle DI, the road to achieve this is very simple :)
With NuGet( package manager) we can easily import unity to our code.
in Visual Studio Tools -> NuGet Package Manager -> Manage Packages for Solution -> in search input write unity -> choose our project-> click install
Now two files with nice comments will be created.
in App-Data folder UnityConfig.cs and UnityMvcActivator.cs
UnityConfig - in RegisterTypes method, we can see type that will be injection in our constructors.
UnityMvcActivator - > also with nice comments which say that this class integrates Unity with ASP.NET MVC
Now we can decouple our Controller from class SantAndHisReindeer :)
There is one final thing we must do before running our application.
In Global.asax.cs we must add new line: UnityWebActivator.Start() which will start, configure Unity and register our types.
Dependency injection using MEF
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0