简体   繁体   中英

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. My current implementation is like the one shown below

IInterface1: ServiceClass

IInterface2: ServiceClass , where IInterface2 inherits from IInterface1

Then in my Startup.cs, I register them as

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. 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. To workaround it, you can use Autofac for example, which allows such scenarios. In asp .net core you have to setup Autofac as DI container . Next, you can register multiple implementations of the same interface. To resolve those use IEnumerable<T> .

One more thing - you don't have to think about DI nor enforce DI. DI mechanism is something outside of your interests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM