当需要同一类型的多个实例时,使用“DI” [英] DI with Unity when multiple instances of the same type is needed

查看:272
本文介绍了当需要同一类型的多个实例时,使用“DI”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助。我使用Unity作为我的容器,我想在我的构造函数中注入两个不同的类型的实例。

I need help with this. I'm using Unity as my container and I want to inject two different instances of the same type into my constructor.

class Example
{
   Example(IQueue receiveQueue, IQueue sendQueue) {}
}

....和IQueue在我的MessageQueue类中实现。

....and IQueue is implemented in my MessageQueue class....

class MessageQueue : IQueue
{
    MessageQueue(string path) {}
}

将两个不同的MessageQueue实例注入到我的Example类中?每个要用不同路径创建的MessageQueue实例。

How can I inject two different instances of MessageQueue into my Example class? Each of the MessageQueue instances to be created with different path.

推荐答案

有很多方法来实现所需的结果(证明通过多个答案)。这是使用命名注册(没有属性)的另一种方法:

There are many ways to achieve the results you want (as evidenced by the multiple answers). Here is another way using named registrations (without attributes):

IUnityContainer container = new UnityContainer();

container.RegisterType<IQueue, MessageQueue>("ReceiveQueue", 
    new InjectionConstructor("receivePath"));

container.RegisterType<IQueue, MessageQueue>("SendQueue",
    new InjectionConstructor("sendPath"));

container.RegisterType<Example>(
    new InjectionConstructor(
        new ResolvedParameter<IQueue>("ReceiveQueue"),
        new ResolvedParameter<IQueue>("SendQueue")));

Example example = container.Resolve<Example>();

这种方法的缺点是,如果Example构造函数被更改,则还必须修改注册码匹配。此外,错误将是一个运行时错误,而不是一个更好的编译时错误。

The downside of this approach is that if the Example constructor is changed then the registration code must also be modified to match. Also, the error would be a runtime error and not a more preferable compile time error.

您可以将以上内容与InjectionFactory结合起来,以手动方式调用构造函数以给出编译时间检查:

You could combine the above with an InjectionFactory to invoke the constructor manually to give compile time checking:

IUnityContainer container = new UnityContainer();

container.RegisterType<IQueue, MessageQueue>("ReceiveQueue",
    new InjectionConstructor("receivePath"));

container.RegisterType<IQueue, MessageQueue>("SendQueue",
    new InjectionConstructor("sendPath"));

container.RegisterType<Example>(new InjectionFactory(c =>
    new Example(c.Resolve<IQueue>("ReceiveQueue"),
                c.Resolve<IQueue>("SendQueue"))));

Example example = container.Resolve<Example>();

如果您使用的是组合根,那么使用魔术字符串(ReceiveQueue和SendQueue )将限于一个注册位置。

If you are using a composition root then the use of the magic strings ("ReceiveQueue" and "SendQueue") would be limited to the one registration location.

这篇关于当需要同一类型的多个实例时,使用“DI”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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