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

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

    I think this has been asked before on Stackoverflow. You need to use ParameterOverride:

    ParameterOverride enables you to pass in values for constructor parameters to override a parameter passed to a given named constructor. Only the parameter value is overridden, not the constructor.

    Link to MSDN Article

    Link to Stackoverflow Article

    var exampleInstance = new Example();
    
    var queue1 = unityContainer.Resolve(new ParameterOverrides { { "path", "yourPath" }});
    
    var queue2 = unityContainer.Resolve(new ParameterOverrides { { "path", "yourPath2Queue2" }});
    
    exampleInstance.Example(queue1,queue2);
    

提交回复
热议问题