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

已配置控制器仍报错:激活CustomerRepository时无法解析ApplicationDbContext

问题解决:Unable to resolve service for type 'Data.ApplicationDbContext'

错误的核心原因是你没有在依赖注入容器中注册ApplicationDbContext。CustomerRepository的构造函数依赖ApplicationDbContext实例,但DI容器找不到对应的服务注册,所以抛出该异常。

解决方案

在ConfigureServices方法中添加ApplicationDbContext的注册代码,以下是基于SQL Server的示例配置:

修改后的ConfigureServices代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // 注册ApplicationDbContext,替换为你的数据库连接字符串配置
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    services.AddScoped<ICustomerRepository, CustomerRepository>();
}

补充说明

  • 需确保appsettings.json中已配置对应连接字符串,示例如下:
    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
    
  • 确认Startup.cs文件已正确引用Data命名空间下的ApplicationDbContext。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:52:00