Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register multiple implementations with single interface

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.

like image 458
Arjun Shetty Avatar asked Jul 26 '13 19:07

Arjun Shetty


People also ask

Can an interface have multiple implementations?

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).

CAN interface have multiple implementations C#?

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.

Should I use transient or scoped?

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.

Is AddHttpClient transient?

In the preceding code, AddHttpClient registers GitHubService as a transient service. This registration uses a factory method to: Create an instance of HttpClient .


1 Answers

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>();
like image 143
nemesv Avatar answered Sep 18 '22 18:09

nemesv