在 ConfigureServices()
方法里将 DbContext
注入到 IHostedService
中,并在 IHostedService
的 StartAsync()
方法里访问数据库。这样可以确保在数据库创建之后才进行访问。
以下是代码示例:
public class MyHostedService : IHostedService
{
private readonly MyDbContext _context;
public MyHostedService(MyDbContext context)
{
_context = context;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _context.Database.EnsureCreatedAsync(); // 确保数据库已创建
// 在这里可以安全地访问数据库
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
public void ConfigureServices(IServiceCollection services)
{
// 添加 DbContext
services.AddDbContext();
// 添加 IHostedService
services.AddHostedService();
}