Home >Backend Development >C#.Net Tutorial >What are AddSingleton, AddScoped and Add Transient C# Asp.net Core?
There are three ways to register dependencies in Startup.cs. ie. AddSingleton, AddScoped and AddTransient.
When we register a type as a singleton, only one instance is available throughout the process. 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 every subsequent request.
public void ConfigureServices(IServiceCollection services){ services.AddSingleton<ILog,Logger>() }
When we register a type as Scoped, an instance is used throughout Apply upon request. When a new request comes, New instance created. Adding a scope specifies that one object is available per object ask.
public void ConfigureServices(IServiceCollection services){ services.AddScoped<ILog,Logger>() }
When we register a type as transient, a new instance will be created every time. Transient Create new instances for each service/controller and for each request per user.
public void ConfigureServices(IServiceCollection services){ services.AddTransient<ILog,Logger>() }
Parameters | Add Singleton | Add Scoped | Add Transient |
---|---|---|---|
Instance | per request/every |
The above is the detailed content of What are AddSingleton, AddScoped and Add Transient C# Asp.net Core?. For more information, please follow other related articles on the PHP Chinese website!