用Unity实例化同一个类中同一个接口的两个对象 [英] Instatiate with Unity two objects of same interface in the same class
问题描述
我有一个案例,我需要为同一个接口实例化两个在同一个类中使用的不同实现.
I have a case where I need to instantiate for the same interface two different implementation that are both used in the same class.
public AutoMapperRegisterFactory(IRegisterAutoMapper registerAutoMapper , IRegisterAutoMapper registerAutoMapperMobile)
{
m_RegisterAutoMapper = registerAutoMapper;
}
我将如何告诉 unity 第一个 IRegisterAutoMapper
应该是 RegisterAutoMapper
类型,第二个应该是 RegisterAutoMapperMobile
类型?>
How would I go about of telling unity that the first IRegisterAutoMapper
should be of type RegisterAutoMapper
and the second of type RegisterAutoMapperMobile
?
推荐答案
您可以使用 IRegisterAutoMapper 的多个命名映射并结合一个 InjectionConstructor 来实现,该 InjectionConstructor 告诉 Unity 为每个参数使用哪些特定映射.
You can do it with multiple named mappings for IRegisterAutoMapper combined with an InjectionConstructor telling Unity what specific mappings to use for each argument.
IUnityContainer container = new UnityContainer()
.RegisterType<IRegisterAutoMapper, RegisterAutoMapper>() //default
.RegisterType<IRegisterAutoMapper, MobileRegisterAutoMapper>("Mobile")
.RegisterType<AutoMapperRegisterFactory>(
new InjectionConstructor(
typeof(IRegisterAutoMapper),
new ResolvedParameter<IRegisterAutoMapper>("Mobile")));
这篇关于用Unity实例化同一个类中同一个接口的两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!