.NET 5使用AddPooledDbContextFactory注册EF上下文后如何自动执行数据库迁移
问题原因
你调用AddPooledDbContextFactory<CommanderContext>()注册的是上下文工厂服务,默认不会直接注册CommanderContext类型的服务实例,所以直接从DI容器请求CommanderContext时会抛出找不到服务的异常。
解决方案
方案1:通过工厂创建上下文执行迁移(推荐)
无需修改现有服务注册逻辑,仅调整InitializeDatabase方法,先获取上下文工厂再创建实例执行迁移即可:
private void InitializeDatabase(IApplicationBuilder app) { using var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope(); // 获取已注册的上下文工厂 var contextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<CommanderContext>>(); // 用工厂创建上下文实例 using var context = contextFactory.CreateDbContext(); // 执行迁移 context.Database.Migrate(); }
方案2:补充注册上下文服务
如果你项目中其他业务逻辑需要直接注入CommanderContext使用,可以在ConfigureServices方法中补充上下文的服务注册,原有迁移代码无需改动即可正常运行:
public void ConfigureServices(IServiceCollection services) { services.AddPooledDbContextFactory<CommanderContext>(options => { options.UseSqlServer(_configuration.GetConnectionString("default")); }); // 新增:补充注册CommanderContext服务 services.AddScoped<CommanderContext>(sp => sp.GetRequiredService<IDbContextFactory<CommanderContext>>().CreateDbContext()); services.AddGraphQLServer() .AddQueryType<Query>() .AddMutationType<Mutation>() .AddFiltering() .AddSorting() .AddProjections(); }
注意事项
开发环境自动执行迁移是合理的,生产环境建议使用独立的迁移脚本、发布任务来执行迁移操作,避免自动迁移引发的意外数据丢失。
内容的提问来源于stack exchange,提问作者Sheheryar Sajid
相关产品推荐
相关产品推荐

