Search code examples
c#dependency-injectionunity-containerienumerable

Resolving IEnumerable<T> with Unity


Can Unity automatically resolve IEnumerable<T>?

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

public CoalescingParserSelector(IEnumerable<IParserBuilder> parserBuilders)

and I configure individual IParserBuilder instances in the container:

container.RegisterType<IParserSelector, CoalescingParserSelector>();
container.RegisterType<IParserBuilder, HelpParserBuilder>();
container.RegisterType<IParserBuilder, SomeOtherParserBuilder>();

can I make this work without having to implement a custom implementation of IEnumerable<IParserBuilder>?

var selector = container.Resolve<IParserSelector>();

So far I haven't been able to express this in any simple way, but I'm still ramping up on Unity so I may have missed something.


Solution

  • It turns out that this is actually awfully simple to do:

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

    Unity natively understands arrays, so we just need to map the enumerable to an array of the same type.