<分区>
我的 .net 核心应用程序需要在指定的时间间隔内抓取数据。我选择实现 IHostedService
以与 API 并行运行它。托管服务需要注入(inject)一些服务。我在 startup.cs
中注册它们,但出现错误:
System.InvalidOperationException: 'Cannot consume scoped service 'IXService' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'.'
我的 startup.cs:
services.AddScoped<IXService, XService>();
services.AddHostedService<MyHostedService>();
我在使用 DbContext 时遇到了类似的问题,我用 https://stackoverflow.com/a/48368934/8475133 解决了它, 但这次我需要依赖注入(inject)穿过更深的层并在每个层中处理 IServiceScopeFactory 似乎不是一个优雅的解决方案。