如何解决为什么托管服务需要其依赖服务是 AddScoped()?
根据官方documentation:
要在 BackgroundService 中使用范围服务,请创建一个范围。默认情况下,不会为托管服务创建范围。
没关系,这就是示例代码所做的:
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();
await scopedProcessingService.DoWork(stoppingToken);
}
但是当 IScopedProcessingService
服务在 IHostBuilder.ConfigureServices
(Program.cs) 中注册时,它添加了 AddScoped
:
services.AddScoped<IScopedProcessingService,ScopedProcessingService>();
这有必要吗?根据 this,AddScoped()
将 ScopedProcessingService
的范围限定为 Http 请求的生命周期。但是,这是一个后台服务,因此没有 Http 请求。如果我将代码更改为使用 AddTransient()
,它运行良好:
services.AddTransient<IScopedProcessingService,ScopedProcessingService>();
如果在 Http 请求(例如,控制器)中运行的某些代码尝试解析 AddScoped()
服务,IScopedProcessingService
是必要的还是仅仅是性能优化?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。