I'm trying to register multiple DbContext implementations in aspnet core DI
so I registered DbContext as bellow
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);
}
});
so from repositories, I'm trying to request instance like below
private readonly IDbContext _context;
public Repository(Func<DbContextType, IDbContext> resolver)
{
_context = resolver(DbContextType.TnA);
}
But when I run the application it throws an exception as below
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Web.Areas.TestController Lifetime: Transient ImplementationType: Web.Areas.TestController': Unable to resolve service for type 'Data.IDbContext' while attempting to activate 'Service.InterfaceService'.)
Basically almost all services and controller complaining about the same issue. So what was the missing part?
UPDATE
Actually I made some changes on registering DB context now it work
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);
}
});
IDbContextwith the IoC container.Func<DbContextType, IDbContext> resolverand resolve usingvar context = resolver(DbContextType.TnA);It worked perfectly Thanks