DI with Unity when multiple instances of the same type is needed

前端 未结 6 1636
忘了有多久
忘了有多久 2021-01-02 09:12

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
{
           


        
6条回答
  •  心在旅途
    2021-01-02 09:39

    You could register the two instances with names:

    myContainer.RegisterInstance("ReceiveQueue", myReceiveMessageQueue);
    myContainer.RegisterInstance("SendQueue", mySendMessageQueue);
    

    and then you should be able to resolve by name, but it requires using the Dependency attribute:

    class Example
    {
        Example([Dependency("ReceiveQueue")] IQueue receiveQueue, 
                [Dependency("SendQueue")] IQueue sendQueue) {
       }
    }
    

    or inject the unity container and then resolve the instances within the constructor:

    class Example
    {
        Example(IUnityContainter container) 
        {
            _receiveQueue = container.Resolve("ReceiveQueue");
            _sendQueue = container.Resolve("SendQueue");
        }
    }
    

提交回复
热议问题