NetCore EfCore中如何将DbContext实例注入IHostedService?

强才捷
2023-12-01
public class MyBackgroundService : IHostedService, IDisposable
{
    private readonly IHostApplicationLifetime appLifetime;
    private readonly IServiceScopeFactory scopeFactory;
    
    public MyBackgroundService(IHostApplicationLifetime _appLifetime, IServiceScopeFactory _scopeFactory)
    {
        this.appLifetime = _appLifetime;
        this.scopeFactory = _scopeFactory;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<Context.MyDbContext>();
            //此处的Context.MyDbContext是你的DbContext实例
            //to do ....
        }
    }
    public Task StopAsync(CancellationToken cancellationToken)
        {

            return Task.CompletedTask;
        }

        public void Dispose()
        {

        }
}
 类似资料: