We know what Dependency Injection and Dependency Inversion are, but what exactly happens to these dependencies in terms of how long they live. This is where Service Lifetimes come into play. There are three Service Lifetimes in csharp.
- Transient Service Lifetime
When its okay to instantiate a dependency anytime you need it, so when the request comes in, the
IServiceProvider, will resolve, construct and inject a brand new instance of the dependency, and
it further constructs and injects a new instance of the dependency based on subsequent requests.
AddTransient<DependencyName>(); // marks the dependency as transient- Scoped Service Lifetime
What if the dependency tracks some sort of state that needs to be shared across multiple classes,
this is where the Scoped Lifetime comes into place. Here, when an HTTP request arrives, the
IServiceProvider resolves, constructs and injects a new instance of the dependency, but if there
is any other service that participates in that Http request and also depends our dependency, then
they will receive the same instance of the dependency. But then if a new request comes in, the
dependency is newly constructed and injected.
In short, Scoped Lifetime services are created once per HTTP Request and reused within that request.
AddScoped<DependencyName>(); // marks it as scoped- Singleton Service Lifetime:
What if our dependency is expensive to instanciate, or it tracks state that needs to be shared
with all classes that request it during the lifetime of our application, then we would mark it
with the AddSingleton method. Now any and all services that depend on this dependency will
receive the same instance of the dependency.
In short, singleton lifetime services are created the first time they are requested and reused across the application lifetime
AddSingleton<DependencyName>(); // marks it as a singleton