Resolving IEnumerable with Unity

前端 未结 8 1090
梦如初夏
梦如初夏 2020-12-04 22:05

Can Unity automatically resolve IEnumerable?

Let\'s say I have a class with this constructor:

public CoalescingParserSelector(I         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 22:35

    @Metro Smurf: your answer got me in the right track: Unity is unable to automatically resolve IEnumerable dependencies.

    I wasn't able to compile your example since the RegisterType method doesn't take an InjectionConstructor instance as parameter.

    Also note that the ResolveAll method will only work if you've registered multiple types with different names and also this method does NOT return an instance for the default (unnamed) registration. (I completely disagree with this behavior btw).

    This is what worked for me:

    container.RegisterType("HelpParserBuilder");
    container.RegisterType("SomeOtherParserBuilder");
    container.RegisterType();
    
    container.Configure().ConfigureInjectionFor(new InjectionConstructor(container.ResolveAll()));
    

    In order to resolve a single instance you will need to also add a default registration otherwise the call to Resolve() will fail.

    This code makes the default registration to enable single resolution:

    container.RegisterType();
    IParserBuilder builder = container.Resolve()
    

提交回复
热议问题