与统一在同一类同一接口的两个对象进行启动[英] Instatiate with Unity two objects of same interface in the same class

本文是小编为大家收集整理的关于与统一在同一类同一接口的两个对象进行启动的处理方法,想解了与统一在同一类同一接口的两个对象进行启动的问题怎么解决?与统一在同一类同一接口的两个对象进行启动问题的解决办法?与统一在同一类同一接口的两个对象进行启动问题的解决方案?那么可以参考本文帮助大家快速定位并解决问题,译文如有不准确的地方,大家可以切到English参考源文内容。

问题描述

我有一种情况,我需要实例化相同接口的两个不同的实现.

public AutoMapperRegisterFactory(IRegisterAutoMapper registerAutoMapper , IRegisterAutoMapper registerAutoMapperMobile)
{
   m_RegisterAutoMapper = registerAutoMapper;
}

我将如何告诉unity第一个IRegisterAutoMapper应该是类型RegisterAutoMapper和类型RegisterAutoMapperMobile?

的第二个IRegisterAutoMapper

推荐答案

您可以使用多个命名映射进行IREGISTERAUTOMAPPER与IndectionConstructor的多个命名映射,告诉Unity每个参数要使用哪种特定映射.

IUnityContainer container = new UnityContainer()
    .RegisterType<IRegisterAutoMapper, RegisterAutoMapper>() //default
    .RegisterType<IRegisterAutoMapper, MobileRegisterAutoMapper>("Mobile")
    .RegisterType<AutoMapperRegisterFactory>(
        new InjectionConstructor(
            typeof(IRegisterAutoMapper), 
            new ResolvedParameter<IRegisterAutoMapper>("Mobile")));

本文地址:https://www.itbaoku.cn/post/2352620.html

问题描述

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 ?

推荐答案

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")));
查看更多