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

前端 未结 6 1597
忘了有多久
忘了有多久 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:55

    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("ReceiveQueue", 
        new InjectionConstructor("receivePath"));
    
    container.RegisterType("SendQueue",
        new InjectionConstructor("sendPath"));
    
    container.RegisterType(
        new InjectionConstructor(
            new ResolvedParameter("ReceiveQueue"),
            new ResolvedParameter("SendQueue")));
    
    Example example = container.Resolve();
    

    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.

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

    IUnityContainer container = new UnityContainer();
    
    container.RegisterType("ReceiveQueue",
        new InjectionConstructor("receivePath"));
    
    container.RegisterType("SendQueue",
        new InjectionConstructor("sendPath"));
    
    container.RegisterType(new InjectionFactory(c =>
        new Example(c.Resolve("ReceiveQueue"),
                    c.Resolve("SendQueue"))));
    
    Example example = container.Resolve();
    

    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.

提交回复
热议问题