依赖注入的ASP.NET Core多重实现

时间:2019-04-27 20:58:25

标签: c# asp.net-core dependency-injection

有没有一种方法可以使用ASP.NET Core指定单个接口的多个实现?我可以在Ninject中这样做:

ninjectKernel.Bind<DbContext>().To<OracleDbContext>().Named("UnitWork");
ninjectKernel.Bind<DbContext>().To<AppsDbContext>().Named("AppsWork");

2 个答案:

答案 0 :(得分:0)

如果您的问题仅针对DbContext,那么使用以下语句很容易

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<OracleDbContext>(builder => builder.UseSqlServer(connectionString));
    services.AddDbContext<AppsDbContext>(builder => builder.UseSqlServer(connectionString));
}

如果您的问题与通用接口有关,则只有在通用接口时才有可能。假设您有一个如下所示的界面:

public interface IRepository<T>
{
}

以及多种实现方式,例如:

public class GenericRepository<User> : IRepository<User>
{
}

public class GenericRepository<Order> : IRepository<Order>
{
}

您只需要一行即可注册多个实现。

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<>));
}

我希望这对您有帮助

答案 1 :(得分:0)

我还发现您可以在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);