Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
104 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...