0

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.