mspasiuk mspasiuk - 23 days ago 10
C# Question

Unity container, how to inject an specific class based on the "calling" class

I have the following snippet

public static void RegisterComponents(IUnityContainer container)
{
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<ISocialClient, ClientA>("a");
container.RegisterType<ISocialClient, ClientB>("b");
container.RegisterType<ISocialClient, ClientC>("c");

GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}


this is WebApi2 project.
So I have 3 controllers,

public class SocialAController : ApiController
{
private ISocialClient client;
...
}


Is there a way in Unity to configure, for SocialAController get the "ClientA" implementation, for SocialBController get the "ClientB" implementation?

Answer

mspasiuk,

You can do this by registering for example SocialAController this way:

    container.RegisterType<SocialAController>(new InjectionConstructor(new ResolvedParameter<ISocialClient>("a")));
Comments