C# Dependency Injection — Service Lifetimes
What is Dependency Injection?
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
A design methodology where rather than the caller creating the instance, it is injected by some framework or some other mechanism.
It helps to implement decoupled architecture where you change at one place and changes are reflected in many places.
Types of Dependency Lifetime
1. Singleton
Created only for the first request. If a particular instance is specified at registration time, this instance will be provided to all consumers of the registration type. Objects are the same for every request.
Used: Caching, Shared Services, Hit Counter.
2. Transient
For every request, a new instance will be created. In the same request, if we do dependency injection multiple times different instances will be injected. Objects are always different.
Used: Instances should not affect each other like different transactions, Thread safety as objects are different instances, the same object asked multiple times in the constructor.
3. Scoped
Objects are the same for a given request but different across each new request.
Used: Repository for the same transaction, Business Objects, Used most of the time.