1.BackgroundService注入的服务默认为Singleton范围:
services.AddHostedService<SyncDataJob>();
或者
services.AddSingleton<IHostedService,SyncDataJob>();
2.运行时,会报错:
Cannot consume scoped service from singleton
3.解决办法:
a:使用IServiceScopeFactory 工厂
public SyncDataJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
ISyncConfigService syncConfigService=scope.ServiceProvider.GetRequiredService<ISyncConfigService>();
var syncConfigEntity = syncConfigService.GetEntityByType(CONFIG_TYPE);
while (!stoppingToken.IsCancellationRequested)
{
//Doing Somethings
var isSuc = this.AddFetchJob();
await Task.Delay(syncConfigEntity.Data.delay * 1000, stoppingToken);
}
}
}
https://www.5axxw.com/questions/content/rvyfhj
b:使用IServiceProvider
public ConsumeScopedServiceHostedService(IServiceProvider services,
ILogger<ConsumeScopedServiceHostedService> logger)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service running.");
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();
await scopedProcessingService.DoWork(stoppingToken);
}
}
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio