Search code examples
c#-4.0dependency-injectioninversion-of-controlunity-container

Unity Container resolve a Dictionary of objects with same Interface


I got the following block

 container.RegisterType<IService, ServiceA>("a");
 container.RegisterType<IService, ServiceB>("b");

I want to have a Dictionary of type Dictionary<string,IService>.

I will receive service name by parameter in an API rest and my idea is based on that parameter get the implementation I need from the Dictionary.

I can't figure out how to inject the Dictionary (with the resolved classes inside) into my business class. I want to do something like this.

private readonly IDictionary<string,IService> serviceDictionary;

public ClassConstructor (IDictionary<string,IService> dictionary)
{
    this.serviceDictionary = dictionary;
}

Solution

  • You should not inject IDictionary<string,IService> into your component, but instead an application-tailored abstraction:

    public interface IServiceProvider
    {
        IService GetService(string key);
    }
    

    This way you can create an implementation for Unity as follows:

    public class UnityServiceProvider : IServiceProvider
    {
        public IUnityContainer Container { get; set; }
    
        public IService GetService(string key) => Container.Resolve<IService>(key);
    }
    

    Now you can complete your registration as follows:

    container.RegisterType<IService, ServiceA>("a");
    container.RegisterType<IService, ServiceB>("b");
    container.RegisterInstance<IService>(new UnityServiceProvider { Container = container });
    container.RegisterType<ClassConstructor>();