Question

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.

Was it helpful?

Solution

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>();

OTHER TIPS

I was faced with the same issue. I found a workaround, you can select the implementation depending on the consumer (I wish it were the other way around!). See the example below:

container.RegisterConditional<IInterface1, Myclass1>(
            c => c.Consumer.ImplementationType == typeof(Myclass2Service));
container.RegisterConditional<IInterface1, Myclass2>(
            c => c.Consumer.ImplementationType == typeof(Myclass2Service));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top