[英]How to register same interface multiple times in .Net Core?
I'm trying to register 2 interfaces implemented by the same class in different ways.我正在尝试以不同方式注册由同一个 class 实现的 2 个接口。 My current implementation is like the one shown below我当前的实现如下所示
IInterface1: ServiceClass
IInterface2: ServiceClass
, where IInterface2 inherits from IInterface1 IInterface2: ServiceClass
,其中 IInterface2 继承自 IInterface1
Then in my Startup.cs, I register them as然后在我的 Startup.cs 中,我将它们注册为
services.AddScoped<IInterface1>(x => {return ServiceClass(ConnectionString1)})
services.AddScoped<IInterface2>(x => {return ServiceClass(ConnectionString2)})
services.AddScoped<IInterface1>(x => {return ServiceClass(ConnectionString1)})
services.AddScoped<IInterface2>(x => {return ServiceClass(ConnectionString2)})
The problem is I'm creating a library, so having a redundant interface is not something I would like.问题是我正在创建一个库,所以我不希望有一个冗余接口。 Ideally, I would like to remove IInterface2 from the library.理想情况下,我想从库中删除 IInterface2。 Is there any way I can register the same interface with different parameters?有什么办法可以用不同的参数注册相同的接口吗?
I've looked at all the related questions asked here but all the requirements were different, since most of them had different classes implementing them.我查看了此处提出的所有相关问题,但所有要求都不相同,因为其中大多数都有不同的类来实现它们。
As I know build-in DI cannot do that.据我所知,内置 DI 无法做到这一点。 To workaround it, you can use Autofac
for example, which allows such scenarios.要解决它,您可以使用Autofac
,例如,它允许这种情况。 In asp .net core you have to setup Autofac as DI container .在 asp .net 核心中,您必须将Autofac 设置为 DI 容器。 Next, you can register multiple implementations of the same interface.接下来,您可以注册同一接口的多个实现。 To resolve those use IEnumerable<T>
.要解决这些问题,请使用IEnumerable<T>
。
One more thing - you don't have to think about DI nor enforce DI.还有一件事——您不必考虑 DI 也不必强制执行 DI。 DI mechanism is something outside of your interests. DI 机制超出了您的兴趣范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.