Instatiate with Unity two objects of same interface in the same class

两盒软妹~` 提交于 2019-12-11 17:59:47

问题


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

How would I go about of telling unity that the first IRegisterAutoMapper should be of type RegisterAutoMapper and the second of type RegisterAutoMapperMobile ?


回答1:


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")));


来源:https://stackoverflow.com/questions/17570488/instatiate-with-unity-two-objects-of-same-interface-in-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!