且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-16 14:46:41

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

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

我希望这对您有帮助