Dependency injection of two or more classes implementing the same interface

Asked

Viewed 175 times

0

The entire architecture of my system is based on addiction injection, where in my configureServices I configure the injections as follows

services Addscoped();

However the need arose for me to have to use 2 classes that implement 1 Interface and based on a value I spend in runtime hours instancio a class hours other.

Without injection of dependency I would solve this problem with a Factory.

With dependency injection I’m having difficulty a made that this configuration is made in CONFIGURESERVICES.

How do you usually solve this problem?

  • one of the overloads allows you to pass a Function, which in theory allows a Factory, look at this example https://www.c-sharpcorner.com/article/net-core-dependency-injection-one-interface-multiple-implementation/ I haven’t tested yet

  • Probably the value you pass is not in the application startup, right? If it is, just do an anomia function or even an IF. Now if this happens later, you might want to inject Factory. But it would be nice to exemplify with code, explain better what this class does etc...

  • The value I will pass in the Factory parameter I will only have in a layer below the Webapi where the startup is, in the Applicationservice layer.

  • @Lucasmiranda I did some tests and I think your comment worked

  • The @Lucasmiranda solution worked. Thank you very much

  • cool, Midnight! if you can, answer your own question, it’s something interesting and possibly someone will show up here with that question too

  • I replied @Lucasmiranda but stackoverflow converted into comment and stayed that way. Perhaps it’s interesting you answer and then I confirm as correct answer

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.