ResolveAll in IoC

I have a need to be able to register and inject all implementations of an interface, to build various processors for incoming and outgoing requests to other systems.

If I have 20-30 implementations of each (request and response) processor, is there no way to inject IEnumerable and IEnumerable into a service?

This is a fairly standard thing in all IoC containers I’ve used (SimpleInjector, StructureMap).

An interface can only have a single implementation and we specifically avoid any IOC magic that can hurt runtime performance.

If you wanted to register all concrete types you can do that by scanning to find all types and pre-registering them with:

var fooTypes = assembly.GetTypes().Where(x => x.HasInterface(typeof(IFoo)));

I’m assuming you’d just be able fetch a collection with all of them with something like:

container.Register<IEnumerable<IFoo>>(c => fooTypes.Select(c.Resolve).Cast<IFoo>());

/* Type can also be inferred and condensed to */
container.Register(c => fooTypes.Select(c.Resolve).Cast<IFoo>()); 
1 Like

Thank you! I think this will work, although I would still love to see this feature added.

I don’t know if I agree with the performance / IOC magic comment. This feature has become a staple in my toolbox on just about every project I’ve worked on. It allows one to build light weight rule engines, business logic validators, define actions that can be taken by a user on an entity based on conditions - all defined in a singular, testable unit of code that can be aggregated and run over an entity. This let’s my code stick to the S in SOLID, which ServiceStack also compliments.

You can propose a feature request for it but it’s never been requested before and I’ve never needed it, even if I did I’d avoid pushing it down and coupling it to an IOC. I’d rather manage the instances in user code with a manager class, e.g:

container.Register(c => new BusinessRules(fooTypes));

Where access is governed by an explicit API and it’s clear exactly how it works and remains completely debuggable.

1 Like

Fair enough, thank you sir.