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

.NET Core 5 DbContext注入引发AggregateException与InvalidOperationException

解决.NET Core 5中DbContext依赖注入的构造函数异常问题

问题场景

解决方案包含三个.NET Core 5项目:

  • Demo.DAL(类库):存放数据访问层代码,包含App_DbContext类
  • Demo.BLL(类库):业务逻辑层
  • Demo.PL(MVC):表现层,负责依赖注入配置

在Demo.PL的Startup中配置AddDbContext后,运行项目或执行数据库迁移时出现以下异常:

AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Demo.DAL.Data.App_DbContext Lifetime: Scoped ImplementationType: Demo.DAL.Data.App_DbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'Demo.DAL.Data.App_DbContext'.)
Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable serviceDescriptors, IServiceProviderEngine engine, ServiceProviderOptions options)

InvalidOperationException: Error while validating the service descriptor 'ServiceType: Demo.DAL.Data.App_DbContext Lifetime: Scoped ImplementationType: Demo.DAL.Data.App_DbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'Demo.DAL.Data.App_DbContext'.
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)

问题根源

App_DbContext的构造函数依赖的是DbContextOptions<DbContext>(基类泛型),但通过AddDbContext<App_DbContext>注册到DI容器的是DbContextOptions<App_DbContext>(当前类泛型),两者属于不同的服务类型,导致容器无法找到匹配的依赖项。

修复步骤

1. 修改Demo.DAL中的App_DbContext构造函数

将构造函数的泛型参数从DbContextOptions<DbContext>改为DbContextOptions<App_DbContext>,确保与注册的服务类型匹配:

namespace Demo.DAL.Data
{
    public class App_DbContext : DbContext
    {
        // 修正泛型参数为当前DbContext类型
        public App_DbContext(DbContextOptions<App_DbContext> options): base(options)
        {

        }
        public DbSet<Department> Departments { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
    }
}

2. 保留Demo.PL的Startup配置(无需修改)

原有的AddDbContext配置是正确的,只需确保appsettings.json中已正确配置连接字符串myConnection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext<App_DbContext>(optionsBuilder =>
    {
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("myConnection"));
    });
}

3. 重新执行数据库迁移(若需要)

打开包管理器控制台,设置默认项目为Demo.DAL,依次执行以下命令:

Add-Migration InitialCreate
Update-Database

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:15:07