用Unity实例化同一个类中同一个接口的两个对象 [英] Instatiate with Unity two objects of same interface in the same class

查看:52
本文介绍了用Unity实例化同一个类中同一个接口的两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例,我需要为同一个接口实例化两个在同一个类中使用的不同实现.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆