gpt4 book ai didi

.net - 如果没有明确定义,aspnetcore 中服务的默认生命周期是多少?

转载 作者:行者123 更新时间:2023-12-05 04:06:47 25 4
gpt4 key购买 nike

我理解的三大人生:

  1. 单例
  2. 有范围
  3. 短暂的

但我似乎找不到说明默认生命周期是多少(如果未明确定义)的文档。

最佳答案

默认情况下,注册类型的生命周期是 transient 的,即每次注入(inject)对象类型时都会创建一个新实例。

注入(inject)生命周期的文档在这里...

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options

Transient

Transient lifetime services are created each time they're requested. This lifetime works best for lightweight, stateless services.

Scoped

Scoped lifetime services are created once per request.

Singleton

Singleton lifetime services are created the first time they're requested (or when ConfigureServices is run if you specify an instance there) and then every subsequent request will use the same instance

aspnetcore 的服务注册要求你使用诸如

的方法显式定义生命周期
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddScoped<IRoleHelper, PermissionRoleHelper>();
services.AddSingleton<IPermissionHelper, ApplicationPermissions>();

诸如 autofac 之类的第 3 方注入(inject)框架会将对象注册为 transient 对象,而无需为对象显式定义备用生命周期范围。

关于.net - 如果没有明确定义,aspnetcore 中服务的默认生命周期是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com