Posted by Anuraj on Wednesday, November 19, 2014 Reading time :2 minutes
Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client’s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. The pattern is used to create program designs that are loosely coupled and testable.
Types of Dependency Injection
In ASP.NET 5, dependency injection is a first class citizen. While in the previous versions of the framework, DI was partially supported, in ASP.NET 5 it is available throughout the entire stack. A minimalistic DI container is provided out of the box, but you can use your own container (BYOC - Bring Your Own Container support).
The default dependency injection supports following life styles.
|Instance||A specific instance is given all the time. You are responsible for its initial creation|
|Transient||A new instance is created every time|
|Singleton||A single instance is created and it acts like a singleton|
|Scoped||A single instance is created inside the current scope. It is equivalent to Singleton in the current scope|
A popular feature for DI in web applications is to create objects that have a single instance per web request. This means that the objects acts as a singleton inside that request but two distinct requests will have different instances of the objects.
In this post, I am injecting database repository to the controller with scoped life style - runtime will create instance of repository on every web request. Here is the changes required in the Startup.cs.
And in the controller, create a constructor, which accepts IUserRepository parameter, which will be injected by runtime while creating the instance of contolller.
Here is the IUserRepository interface and its implementation.
You can find more details about Dependency Injection in ASP.NET vNext here
Happy Programming :)