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

注入DbContext后无法运行API控制器,报错无数据库提供程序配置

问题解决方案

核心问题分析

错误根源是代码中存在手动实例化PokerContext的路径,该路径未配置数据库提供程序:

  • Logic的无参构造函数手动创建Repository实例,若Repository内部直接new PokerContext()(调用无参构造),这个无参构造没有任何数据库配置,会触发错误。
  • PokerContext中多余的ConfigureServices方法和无参构造函数,干扰了依赖注入的正常工作。

分步修复

1. 清理PokerContext类

移除无参构造函数和多余的服务配置方法,强制仅通过依赖注入获取实例:

public class PokerContext: DbContext
{
    public PokerContext(DbContextOptions<PokerContext> options)
        : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Attendee> Attendees { get; set; }
    public DbSet<Event> Events { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

2. 修改Logic类,强制依赖注入

删除无参构造函数,仅保留带Repository参数的构造函数,让DI容器自动注入实例:

public class Logic
{
    private readonly Repository _repo;

    public Logic(Repository repo)
    {
        _repo = repo;
    }
}

3. 注册Repository到依赖注入容器

在Program.cs的服务注册区域添加:

builder.Services.AddScoped<Repository>();

4. 确保Repository正确接收PokerContext

Repository必须通过构造函数注入PokerContext,禁止手动实例化:

public class Repository
{
    private readonly PokerContext _context;

    public Repository(PokerContext context)
    {
        _context = context;
    }

    // 数据操作方法
}

5. 验证连接字符串配置

检查appsettings.json中PokerConnex连接字符串是否正确:

{
  "ConnectionStrings": {
    "PokerConnex": "Data Source=(localdb)\\MSSQLLocalDB; Initial Catalog=PokerAppData; Trusted_Connection=True;"
  }
}

关键注意点

  • 业务逻辑层禁止手动实例化DbContext,必须通过依赖注入获取,保证配置一致性。
  • DbContext类中不要添加服务注册逻辑,统一在Program.cs中管理服务配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:20:40