.NET Dependency Injection overview ( Spring, Unity, Ninject, ….)
Dependency injection (DI) is a mechanism to implement inversion of control principle. It is to create dynamically (inject) dependencies between different classes based on a configuration file description or loaded programmatically. And the dependencies between software components are not expressed in the static code but determined dynamically at runtime.
Many .NET programmers are asking what DI tools to use ?
We have worked on Spring.NET DI as shown here Dependency Injection using SPRING.NET.
Now we are going to show how to use Dependency injection with Unity, Ninject and try to evidence Strengths and weaknesses of each other.
Evry one can build its own Dependency Injection Framework , so lets start from showing what is DI.
1. Building a dependency Injection Framework
Suppose we have a Product Class :
Lets create a IProductRepository interface and implement it :
Now create an ProductService class to use our Repository
You can find that ProductService depends on ProductRepository. Basically, we have ProductRepository objects creating a dependency between ProductService.
This can be troublesome when we want to run some unit tests on ProductService, especially if repository is something that does complex disk or network access.
So now we’re looking at mocking repository but also somehow intercepting the factory call. Very hard to do.
A solution is to pass the repository in as an argument to the constructor. Now you’ve moved the problem elsewhere, but testing can become lots easier.
We pass the needed dependencies in to the constructor or via property setters, and we make it somebody else’s problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph)
According to SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) , Dependency inversion principle are not respected : One should “Depend upon Abstractions. Do not depend upon concretions”.
So we are going to do Dependency Injection.
So it is very easy to change class implementation without having to change any implemetation somewhere else.
We have used 3 repositories to implement 3 different maners of retrieving data.
2. dependency Injection using Unity
Coming Soon