Hello!
Just a quick question, is it possible to resolve multiple instances of the same protocol? So that the resolution returns an array, instead of having to resolve it one by one?
Thanks and sorry if it is stated on the documentation as I couldn't find it.
You should be able to register like so:
container.register([MyProtocol].self) { r in ... }
You'd then use a for loop to resolve however many instances you want, and add them to an array. You can use arguments to specify how many instances to create as well.
Thanks @mpdifran for answering. In addition, maybe name property on register and resolve can be used in @Mijail's case.
I have them registered by name right now, I was wondering If I could recover all of them with some function.
I guess I will register all of them in the same place, to make it like an array. It kinda messes up things a little bit as sometimes I need them separately but I guess it is the best approach.
@mpdifran's answer will work, but it means that when you register the array, you have to be sure that you are aware of all instances and in future when you add or delete a new one, you also have to remember to update the array.
MY preferred option would be over loads that effectively look like this:
func resolve<Service>(_ type:Service.type) -> [Service] {...}
However looking through the source it appears that some quite low level code changes would be required.
being able to return a list of objects that conform to some protocol without having to first manually create an array would make life a lot simpler.
Now that #330 has been merged, this is implementable as a separate behavior as suggested in #322.
I'm not sure though whether this should be part of the Swinject though, as it is quite specific usecase, and can be implemented using public API.
Another way to tackle this would be to extend the InstanceWrapper concept so that you could have InstanceWrapper aggregating results of multiple service entries. Benefit of this approach would be better performance, but would require the refactoring of internal implementation.
What do you guys think?
Closing due to inactivity
Most helpful comment
@mpdifran's answer will work, but it means that when you register the array, you have to be sure that you are aware of all instances and in future when you add or delete a new one, you also have to remember to update the array.
MY preferred option would be over loads that effectively look like this:
However looking through the source it appears that some quite low level code changes would be required.
being able to return a list of objects that conform to some protocol without having to first manually create an array would make life a lot simpler.