mspasiuk mspasiuk -4 years ago 106
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 Source


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

    container.RegisterType<SocialAController>(new InjectionConstructor(new ResolvedParameter<ISocialClient>("a")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download