Resolving IEnumerable with Unity

前端 未结 8 1077
梦如初夏
梦如初夏 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:42

    The

    container.RegisterType<IEnumerable<IParserBuilder>, IParserBuilder[]>();
    

    Worked for me only keep in mind that when you register IParserBuilder types with your container an unique name is required otherwise it will Always be an empty array. So use

    container.RegisterType<IParserBuilder, RealParserBuilder>("UniqueName");
    
    0 讨论(0)
  • 2020-12-04 22:46

    I believe you'll need to use the ResolveAll method and use an explicit InjectionConstructor object, i.e.:

    container.RegisterType<IParserBuilder, HelpParserBuilder>();
    container.RegisterType<IParserBuilder, SomeOtherParserBuilder>();
    
    var injectedBuilders = new InjectionConstructor(container.ResolveAll<IParserBuilder>());
    container.RegisterType<IParserSelector, CoalescingParserSelector>(injectedBuilders);
    

    In other words, I don't think Unity is able to automatically resolve all instances of a type and know to use constructor injection on a class with an IEnumerable parameter without an explicitly declaring an InjectionConstructor object at Run Time.

    Granted I'm still learning Unity as well, but this has been my experience (YMMV).

    0 讨论(0)
提交回复
热议问题