之前在控制台程序中学习如何运行后台任务,ASP.NET Core中其实也有同样的方法BackgroundService ,本以为跟HostedService 没有区别,毕竟BackgroundService 是继承HostedService 的,但实际使用中才发现,依赖注入时,还是有区别的,下面就来说说具体踩到的坑
在服务实现类中,直接注入EF的话,运行时会报错,查了stackoverflow后知道,这里不能直接注入EFContext是因为生命周期问题,BackgroundService是asp.net core开始到结束,而EFContext注入的生命周期是Scoped,在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内),所以在启动时,会提示我们把EFContext改为单例注入
所以,代码需要修改成这样
public class DBHostedService : BackgroundService
{
private readonly ILogger _logger;
private readonly IServiceScopeFactory _scopeFactory;
public DBHostedService(ILogger<DBHostedService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _scopeFactory.CreateScope())
{
var _context = scope.ServiceProvider.GetRequiredService<EFContext>();
await _context.Database.EnsureDeletedAsync();
if (await _context.Database.EnsureCreatedAsync())
{
if (!_context.QuartInfo.Any())
{
var goodList = new List<QuartzInfo>()
{
new QuartzInfo(){
guid = Guid.NewGuid().ToString(),
triggerGroup = "TestGroup1",
triggerName = "TestName",
cronExpression = "0 0/1 * * * ? ",
fullClassName = "BackgroundServiceDemo.TestJob",
jobGroup = "jobGroup1",
jobName = "jobName1",
},
};
_context.QuartInfo.AddRange(goodList);
await _context.SaveChangesAsync();
}
}
}
}
}
参考资料: ASP.NET Core 2.1 : 十一. 如何在后台运行一个任务 How should I inject a DbContext instance into an IHostedService
|
请发表评论