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

WBOY
Release: 2023-09-05 22:21:17
forward
1566 people have browsed it

什么是 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>()
}
Copy after login

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>()
}
Copy after login

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>()
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!