C# – IoC – Multiple implementations support for a single interface

ccastle-windsorinversion-of-controlioc-container

I am wondering why .Net IoC containers do not easily support multiple implementations for a single interface! May be I am wrong, but as far I have seen, frameworks like Ninject partially supports this feature using annotations (how?). I do not think other frameworks like Windsor or simple injector have an easy mechanism to support this scenario.

Is there any reason why this is not supported by many frameworks? AFAIK, one of the most important reasons to use interfaces is to achieve loose coupling. If the frameworks designed to improve loose coupling, do not fluently support multiple implementations for a single interface, I do not understand why!

P.S. Of course I understand that there will be a resolution issue during run time, and the container would be confused which implementation to choose, but that is something which has to be considered in the design, right?

Best Answer

Unity has the same functionality

Register named dependency

    var container = new UnityContainer();
    container.RegisterType<IConnector, Connector>("TestConnector");

Resolve by name

    container.Resolve<IConnector>("TestConnector");

the same approach

    [Dependency("TestConnector")]
    public IConnector Connector { get; set; }

Windsor has the same

class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer()
            .Register(Component.For<IConnector>().ImplementedBy<ConnectorA>().Named("ConnectorA"))
            .Register(Component.For<IConnector>().ImplementedBy<ConnectorB>().Named("ConnectorB"));

        var connectorA = container.Resolve<IConnector>("ConnectorA");
        Console.WriteLine("Connector type: {0}", connectorA.GetType());
        var connectorB = container.Resolve<IConnector>("ConnectorB");
        Console.WriteLine("Connector type: {0}", connectorB.GetType());
        Console.ReadKey();
    }
}

public interface IConnector
{
}

public class ConnectorA : IConnector
{

}

public class ConnectorB : IConnector
{

}
Related Topic