Register multiple implementations with single interface

bitsmonkey picture bitsmonkey · Jul 26, 2013 · Viewed 12.5k times · Source

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.

Answer

nemesv picture nemesv · Jul 26, 2013

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