asp.net DI系统中DbContext寄存器的多重实现



我正试图在aspnet核心DI 中注册多个DbContext实现

所以我注册DbContext如下

services.AddScoped(c => new CoreDbContext(c.GetService<DbContextOptions<CoreDbContext>>()));
services.AddScoped(c => new TnADbContext(c.GetService<DbContextOptions<TnADbContext>>()));
services.AddScoped<Func<DbContextType, IDbContext>>(provider => key =>
{
switch (key)
{
case DbContextType.Core:
return provider.GetService<CoreDbContext>();
case DbContextType.TnA:
return provider.GetService<TnADbContext>();
case DbContextType.Payroll:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
default:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
}
});

因此,从存储库中,我试图请求像下面这样的实例

private readonly IDbContext _context;
public Repository(Func<DbContextType, IDbContext> resolver)
{
_context = resolver(DbContextType.TnA);
}

但当我运行应用程序时,它会抛出一个异常,如下所示

某些服务无法构建(验证时出错服务描述符"ServiceType:Web.Areas.TestController"生存期:瞬态实现类型:Web.Areas.TestController":尝试时无法解析类型为"Data.IDbContext"的服务激活"Service.InterfaceService"。(

基本上所有服务和控制器都在抱怨同一个问题。那么,缺失的部分是什么呢?

更新

事实上,我在注册DB上下文时做了一些更改,现在它可以了

services.AddScoped<Func<DbContextType, IDbContext>>(provider => key =>
{
switch (key)
{
case DbContextType.Core:
return new CoreDbContext(provider.GetService<DbContextOptions<CoreDbContext>>());
case DbContextType.TnA:
return new TnADbContext(provider.GetService<DbContextOptions<TnADbContext>>());
case DbContextType.Payroll:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
default:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
}
});

所以我提出了如下注册Dbconfigs的解决方案

services.AddScoped<Func<DbContextType, IDbContext>>(provider => key =>
{
switch (key)
{
case DbContextType.Core:
return new CoreDbContext(provider.GetService<DbContextOptions<CoreDbContext>>());
case DbContextType.TnA:
return new TnADbContext(provider.GetService<DbContextOptions<TnADbContext>>());
case DbContextType.Payroll:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
default:
throw new ArgumentOutOfRangeException(nameof(key), key, null);
}
});

并确保IDbContext不会注入任何服务,相反,您可以尝试以下

private readonly IDbContext _context;
public InterfaceService(Func<DbContextType, IDbContext> resolver)
{
_context = resolver(DbContextType.TnA);
}

DbContext类型将是一个枚举,其中包含我需要注入的DB上下文类型

最新更新