Unity容器,如何根据"calling"class注入特定的class
Unity container, how to inject an specific class based on the "calling" class
我有以下片段
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);
}
这是 WebApi2 项目。
所以我有 3 个控制器,
public class SocialAController : ApiController
{
private ISocialClient client;
...
}
在 Unity 中有没有办法配置 SocialAController 获得 "ClientA" 实现,SocialBController 获得 "ClientB" 实现?
mspasiuk,
您可以通过以下方式注册例如 SocialAController 来做到这一点:
container.RegisterType<SocialAController>(new InjectionConstructor(new ResolvedParameter<ISocialClient>("a")));
我有以下片段
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);
}
这是 WebApi2 项目。 所以我有 3 个控制器,
public class SocialAController : ApiController
{
private ISocialClient client;
...
}
在 Unity 中有没有办法配置 SocialAController 获得 "ClientA" 实现,SocialBController 获得 "ClientB" 实现?
mspasiuk,
您可以通过以下方式注册例如 SocialAController 来做到这一点:
container.RegisterType<SocialAController>(new InjectionConstructor(new ResolvedParameter<ISocialClient>("a")));