ASP.NET Core Multiple Implementation for Dependency Injection

不羁岁月 提交于 2021-01-29 08:07:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!