Dependency Injection in ASP.NET 5
November 19, 2014 by Anuraj
.Net ASP.Net CodeProject
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
- Constructor injection: the dependencies are provided through a class constructor. - ASP.NET 5 supports only this.
- Setter injection: the client exposes a setter method that the injector uses to inject the dependency.
- Interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.
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.
**Lifestyle** | **Description** |
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 :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub