依赖注入的ASP.NET Core多重实现 [英] ASP.NET Core Multiple Implementation for Dependency Injection

查看:65
本文介绍了依赖注入的ASP.NET Core多重实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

如果您的问题仅针对 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<>));
}

我希望这对您有帮助

这篇关于依赖注入的ASP.NET Core多重实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆