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

可以通过三种方式在 Startup.cs 中注册依赖项。 IE。 AddSingleton、AddScoped 和 AddTransient。

添加 Singleton

当我们将一种类型注册为单例时,整个过程中只有一个实例可用。 application and for every 请求。

It is similar to having a static object.

The instance is created for the first request and the same is avAIlable throughout the 应用程序和每个后续请求。

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

添加Scoped

当我们将一个类型注册为Scoped时,一个实例在整个 按请求申请。当新的请求到来时, 新实例已创建。添加范围指定每个对象可用一个对象 请求。

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

添加瞬态

当我们将一个类型注册为瞬态时,每次都会创建一个新的实例。瞬态 为每个服务/控制器以及每个请求创建新实例 每个用户。

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

 

 

参数 添加 Singleton 添加 Scoped 添加 Transient
实例 每个请求/每个

user.每个请求一个。不同的 每次。Disposed应用关闭请求结束请求结束Used in当单例 实现是必需的。具有不同 每个用户的行为。重量轻, 每个用户的行为。轻量级和 无状态服务。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。