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

.NET 6中IConfiguration注入异常:DbContext读取连接字符串为空

问题分析与解决方案

核心问题

你的代码存在两个关键问题,导致DbContext中IConfiguration为空:

  1. 无参构造函数被调用:当代码中直接使用new TestContext()创建实例时,不会触发依赖注入,configuration字段未被赋值,进入OnConfiguring方法后读取连接字符串就会返回null,进而抛出ArgumentNullException。
  2. 冗余配置与逻辑冲突:你已经在Program.cs中通过AddDbContext为TestContext配置了连接字符串,此时DbContextOptions已经包含了数据库配置,OnConfiguring方法中的optionsBuilder.IsConfigured应为true,原本不需要再读取IConfiguration。但无参构造函数的存在导致这段逻辑被错误执行。

解决方案

1. 移除无参构造函数(推荐)

删除DbContext中的无参构造函数,确保所有TestContext实例都通过依赖注入容器创建:

public partial class TestContext : DbContext
{
    private readonly IConfiguration _configuration;

    // 只保留带参数的构造函数
    public TestContext(DbContextOptions<TestContext> options, IConfiguration configuration)
        : base(options)
    {
        _configuration = configuration;
    }

    public virtual DbSet<DbScalingLevels> DbScalingLevels { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // 此时optionsBuilder.IsConfigured应为true,这段逻辑不会执行
        if (!optionsBuilder.IsConfigured)
        {
            // 若需保留这段逻辑,先判断_configuration是否为null
            if (_configuration != null)
            {
                var connStr = _configuration.GetConnectionString("OPS_DB");
                optionsBuilder.UseSqlServer(connStr);
            }
        }
    }
}

2. 移除冗余的IConfiguration注册

Program.cs中无需手动注册IConfiguration,ASP.NET Core默认已将其注册为单例服务,删除以下代码:

builder.Services.AddSingleton<IConfiguration>(configuration);

3. 检查代码中是否直接调用无参构造函数

排查项目中所有创建TestContext的代码,确保都是通过依赖注入获取实例,而非直接new TestContext()。例如,在控制器中通过构造函数注入:

public class SomeController : ControllerBase
{
    private readonly TestContext _dbContext;

    public SomeController(TestContext dbContext)
    {
        _dbContext = dbContext;
    }
}

为什么另一个项目正常?

另一个项目能正常运行,大概率是因为代码中没有调用无参构造函数,所有TestContext实例都通过依赖注入创建,此时configuration被正确赋值,且OnConfiguring中的逻辑不会被执行(因为optionsBuilder.IsConfigured为true)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:30:40