You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 5环境下Entity Framework Core DbContextFactory未注册问题求助

问题根本原因

AddDbContextFactory<TContext> 默认仅注册 IDbContextFactory<TContext> 类型的服务,不会自动注册 TContext 本身到DI容器,这就是你直接调用 GetRequiredService<AppContext> 报错的核心原因。


解决方案有两种可选:

方案1:修改数据库初始化逻辑,使用工厂创建上下文

不需要改动现有Startup的注册代码,只需要修改Program.cs里的CreateDbIfNotExists方法,改为从DI容器获取上下文工厂,再生成上下文实例即可:

private static void CreateDbIfNotExists(IHost host)
{
    using (IServiceScope scope = host.Services.CreateScope())
    {
        IServiceProvider services = scope.ServiceProvider;
        try
        {
            // 先获取上下文工厂
            var contextFactory = services.GetRequiredService<IDbContextFactory<AppContext>>();
            // 用工厂创建上下文实例
            using AppContext context = contextFactory.CreateDbContext();
            context.Database.EnsureCreated();
        }
        catch (Exception ex)
        {
            ILogger<Program> logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occured while creating the DB.");
        }
    }
}

这种方案更符合池化上下文的使用规范,也是官方推荐的用法。你后续在业务代码、Hot Chocolate的Resolver里也可以优先通过工厂获取上下文,从根源避免并行请求触发EF Core的线程安全问题。

方案2:注册工厂时同时注册DbContext服务

如果你不想改动现有的初始化逻辑,也可以在调用AddDbContextFactory时指定addDbContext参数为true,这样注册工厂的同时会按照默认规则注册AppContext服务:

services.AddDbContextFactory<AppContext>((s, options) =>
    options
        .UseSqlServer(_config.GetConnectionString("TransactDB"))
        .UseLoggerFactory(s.GetRequiredService<ILoggerFactory>()),
    // 新增该参数,同时注册AppContext服务
    addDbContext: true
);

这种方式下你原有的初始化代码不需要做任何改动,同时也能正常使用上下文工厂。默认注册的AppContext生命周期为Scope,符合常规Web请求的使用逻辑,不会和池化工厂的功能冲突。


内容的提问来源于stack exchange,提问作者TwoTinyTurtles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:36:03