.NET Core 5 DbContext注入引发AggregateException与InvalidOperationException
问题场景
解决方案包含三个.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

