1

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;
}

1 Answer 1

3

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>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.