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.
It turns out that this is actually awfully simple to do:
Unity natively understands arrays, so we just need to map the enumerable to an array of the same type.
If you want to generally support IEnumerable, then you can add this line:
This is he generic version of
@Metro Smurf: your answer got me in the right track: Unity is unable to automatically resolve
IEnumerable<T>
dependencies.I wasn't able to compile your example since the
RegisterType
method doesn't take anInjectionConstructor
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:
In order to resolve a single instance you will need to also add a default registration otherwise the call to
Resolve<T>()
will fail.This code makes the default registration to enable single resolution:
You can do like this:
I believe you'll need to use the ResolveAll method and use an explicit InjectionConstructor object, i.e.:
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).
I did this like so
Which registers everything that implements
IParserBuilder
, so when you add a new one you don't need to add any other code for it to appear in the list of builders.