Home >Backend Development >C#.Net Tutorial >What are AddSingleton, AddScoped and Add Transient C# Asp.net Core?

What are AddSingleton, AddScoped and Add Transient C# Asp.net Core?

WBOY
WBOYforward
2023-09-05 22:21:171624browse

什么是 AddSingleton、AddScoped 和 Add Transient C# Asp.net Core?

There are three ways to register dependencies in Startup.cs. ie. AddSingleton, AddScoped and AddTransient.

Add Singleton

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

Add Scoped

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

Add transient

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
user.One per request. different every time. Disposed Application Close Request Ended Request Ended Used in When a singleton Implementation is required. has different behavior of each user. Light weight, behavior of each user. Lightweight and Stateless service.

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete