AddSingleton vs AddScoped vs AddTransient in ASP.NET Core



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>()
}


Parameter Add Singleton Add Scoped Add Transient
Instance Same each request/ each user. One per request. Different for everytime.
Disposed App shutdown End of request End of request
Used in When Singleton implementation is required. Applications which have different behavior per user. Light weight and stateless services.
Updated on: 2020-09-25T10:55:59+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements