Foi útil?

Pergunta

What is the AddSingleton vs AddScoped vs Add Transient C# Asp.net Core?

CsharpServer Side ProgrammingProgramming

There are three ways by which dependencies can be registered in Startup.cs. i.e. AddSingleton, AddScoped and AddTransient.

Add Singleton

When we register a type as singleton, only one instance is available throughout the application and for every request.

It is similar to having a static object.

The instance is created for the first request and the same is available throughout the application and for each subsequent requests.

public void ConfigureServices(IServiceCollection services){
   services.AddSingleton<ILog,Logger>()
}

Add Scoped

When we register a type as Scoped, one instance is available throughout the application per request. When a new request comes in, the new instance is created. Add scoped specifies that a single object is available per request.

public void ConfigureServices(IServiceCollection services){
   services.AddScoped<ILog,Logger>()
}

Add Transient

When we register a type as Transient, every time a new instance is created. Transient creates new instance for every service/ controller as well as for every request and every user.

public void ConfigureServices(IServiceCollection services){
   services.AddTransient<ILog,Logger>()
}


ParameterAdd SingletonAdd ScopedAdd Transient
InstanceSame each request/ each user.One per request.Different for everytime.
DisposedApp shutdownEnd of requestEnd of request
Used inWhen Singleton implementation is required.Applications which have different behavior per user.Light weight and stateless services.
raja
Published on 25-Sep-2020 14:25:25
Advertisements
Foi útil?
Não afiliado a Tutorialspoint
scroll top