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

.NET 8中如何获取所有已注册的DbContext?注入集合为空的问题

解决注入IEnumerable<DbContext>为空的问题

问题原因

使用AddDbContext<c1>注册上下文时,DI容器仅注册了具体的c1类型服务,并未将其关联到DbContext基类。因此当构造函数请求IEnumerable<DbContext>时,容器找不到匹配的服务实例,返回空集合。

解决方案

方案1:注册时同时映射基类

在添加DbContext后,额外将c1注册为DbContext类型的服务:

services.AddDbContext<c1>(options => 
{
    // 此处配置数据库连接等选项,例如:
    // options.UseSqlServer("YourConnectionString");
})
.AddScoped<DbContext>(sp => sp.GetRequiredService<c1>());

方案2:使用指定服务类型的重载

如果仅存在一个DbContext,可以直接用AddDbContext的重载,指定服务类型为DbContext:

services.AddDbContext<DbContext, c1>(options => 
{
    // 配置数据库选项
});

注意:若有多个DbContext,此方式会导致后注册的覆盖先注册的,不适合多上下文场景。

多上下文场景处理

如果存在多个继承自DbContext的类(如c2、c3),需为每个上下文重复基类映射:

services.AddDbContext<c1>(options => { /* 配置 */ });
services.AddDbContext<c2>(options => { /* 配置 */ });

services.AddScoped<DbContext>(sp => sp.GetRequiredService<c1>());
services.AddScoped<DbContext>(sp => sp.GetRequiredService<c2>());

这样注入IEnumerable<DbContext>时,就能获取到所有注册的上下文实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:35:58