问题
Is there a way I can designate multiple implementations of a single interface using ASP.NET Core? I could do this in Ninject like this:
ninjectKernel.Bind<DbContext>().To<OracleDbContext>().Named("UnitWork");
ninjectKernel.Bind<DbContext>().To<AppsDbContext>().Named("AppsWork");
回答1:
If your question is specific to just DbContext
then it's easy using the following statements
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<OracleDbContext>(builder => builder.UseSqlServer(connectionString));
services.AddDbContext<AppsDbContext>(builder => builder.UseSqlServer(connectionString));
}
If your question relates to general interfaces, then it's possible only if it's a generic interface. Say you have an interface like below:
public interface IRepository<T>
{
}
And multiple implementations like:
public class GenericRepository<User> : IRepository<User>
{
}
public class GenericRepository<Order> : IRepository<Order>
{
}
You only need a single line to register multiple implementations.
public void ConfigureServices(IServiceCollection services)
{
// you can register them with any life time like that e.g. Singleton, Transient
services.AddScoped(typeof(IRepository<>), typeof(GenericRepository<>));
}
I hope this helps
回答2:
I also found you can configure your OracleDbContext(s) like this in Configure Services:
services.AddEntityFrameworkOracle()
.AddDbContext<OracleDbContext>(option => option.UseOracle(Configuration["Data:OracleDbConnection"]), ServiceLifetime.Scoped)
.AddDbContext<AppsDbContext>(option => option.UseOracle(Configuration["Data:AppsbConnection"]), ServiceLifetime.Scoped);
来源:https://stackoverflow.com/questions/55884822/asp-net-core-multiple-implementation-for-dependency-injection