I am currently developping a web API, together with the related website. I was about to add in my Startup.cs my new service :
builder.Services.AddScoped<IUserService, UserService>();
But since then, I am wondering how can we know what "type" of service should we add ? There is a bunch of possibilities :
AddScoped
AddSingleton
AddTransient
AddSession
...
And I think this is possibly confusing. So how can we know what type of service makes the most sense for what we want to add (repositories, services, ...) ? What aspects should we take into consideration ?
Also, what impact does it have on our applications ? Does it change anything regarding security, performance or anything else ?
Thanks.
EDIT : here is a better question/explanation
First of all AddSession
is not a lifetime, it's a call which adds session state support to your ASP.NET Core app.
As for scope types - you should read the documentation carefully:
Both articles have quite a lot in common and describe the support of the dependency injection (DI) software design pattern (which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies) which is build into the framework.
This particular section covers the service lifetimes:
Transient
Transient lifetime services are created each time they're requested from the service container. This lifetime works best for lightweight, stateless services. Register transient services withAddTransient
.
In apps that process requests, transient services are disposed at the end of the request.
Scoped
For web applications, a scoped lifetime indicates that services are created once per client request (connection). Register scoped services withAddScoped
.
In apps that process requests, scoped services are disposed at the end of the request.
When using Entity Framework Core, theAddDbContext
extension method registersDbContext
types with a scoped lifetime by default.
By default, in the development environment, resolving a service from another service with a longer lifetime throws an exception. For more information, see Scope validation.
Singleton
Singleton lifetime services are created either:
- The first time they're requested.
- By the developer, when providing an implementation instance directly to the container. This approach is rarely needed.
Every subsequent request of the service implementation from the dependency injection container uses the same instance.