Is there a way to register a single interface which is implemented by more than one concrete class using [simple-injector] and without using template interface?
say we have 2 classes MyClass1
and Myclass2
and both these classes are implementing IInterface1
Now using [simple-injector] we were not able to do this
container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();
converting existing interface to template interface is kinda a hard job on the existing codebase. Hoping there is some easier out there.
Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Multiple implementations with generic Language limitation, but probably in the future, C# allows you to do it. This interface has three implementations, Cat, Dog, and Human class. To register, add this code.
Use Transient lifetime for the lightweight service with little or no state. Scoped services service is the better option when you want to maintain state within a request. Singletons are created only once and not destroyed until the end of the Application. Any memory leaks in these services will build up over time.
In the preceding code, AddHttpClient registers GitHubService as a transient service. This registration uses a factory method to: Create an instance of HttpClient .
You can register multiple implementation of the same interface with using the RegisterCollection
method (see documentation: Configuring a collection of instances to be returned)
So you need to write:
container.Collection.Register<IInterface1>(typeof(Myclass1), typeof(Myclass2));
And now Simple Injector can inject a collection of Interface1
implementation into your constructor, for example:
public class Foo
{
public Foo(IEnumerable<IInterface1> interfaces)
{
//...
}
}
Or you can explicitly resolve your IInterface1
implementations with GetAllInstances
:
var myClasses = container.GetAllInstances<IInterface1>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With