[英]ASP.NET Core Multiple Implementation for Dependency Injection
Is there a way I can designate multiple implementations of a single interface using ASP.NET Core? 有没有一种方法可以使用ASP.NET Core指定单个接口的多个实现? I could do this in Ninject like this:
我可以在Ninject中这样做:
ninjectKernel.Bind<DbContext>().To<OracleDbContext>().Named("UnitWork");
ninjectKernel.Bind<DbContext>().To<AppsDbContext>().Named("AppsWork");
If your question is specific to just DbContext
then it's easy using the following statements 如果您的问题仅针对
DbContext
那么使用以下语句很容易
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 我希望这有帮助
I also found you can configure your OracleDbContext(s) like this in Configure Services: 我还发现您可以在Configure Services中像这样配置OracleDbContext:
services.AddEntityFrameworkOracle()
.AddDbContext<OracleDbContext>(option => option.UseOracle(Configuration["Data:OracleDbConnection"]), ServiceLifetime.Scoped)
.AddDbContext<AppsDbContext>(option => option.UseOracle(Configuration["Data:AppsbConnection"]), ServiceLifetime.Scoped);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.