在BackgroundService中使用IServiceScopeFactory和IServiceScope来创建新的作用域,并在该作用域中进行数据库操作,以便BackgroundService可以看到数据库更新。
代码示例:
在Startup.cs中配置服务并将DbContext注册为Scoped服务:
public void ConfigureServices(IServiceCollection services)
{
// other configurations
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));
services.AddScoped();
}
在BackgroundService中注入IServiceScopeFactory并使用它来创建新的作用域:
public class MyBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
public MyBackgroundService(ILogger logger, IServiceScopeFactory serviceScopeFactory)
{
_logger = logger;
_serviceScopeFactory = serviceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var myService = scope.ServiceProvider.GetService();
await myService.DoSomethingAsync(stoppingToken);
}
await Task.Delay(5000, stoppingToken);
}
}
}
在IMyService的实现类(MyService)中使用依赖注入的DbContext进行数据库操作:
public class MyService : IMyService
{
private readonly MyDbContext _dbContext;
public MyService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task DoSomethingAsync(CancellationToken stoppingToken)
{
// do some database operations here
await _dbContext.MyEntities.AddAsync(new MyEntity());
await _dbContext.SaveChangesAsync(stoppingToken);
}
}
上一篇:BackgroundService未关闭,没有使用.net核心通用主机设置stoppingToken。
下一篇:BackgroundService在集成测试中阻塞了WebApplicationFactory.CreateClient的完成