6.7 — Multiple Implementations and IEnumerable<TService>¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.6 Registration APIs · Next: 6.8 Factories and open generics
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Register the same interface several times and the container keeps all of them. How you ask decides what you get.
- Ask for
IValidator→ you get the last one registered. - Ask for
IEnumerable<IValidator>→ you get all of them, in registration order. - This is how you build a pipeline of handlers without writing any wiring code.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Multiple registration | a container behaviour | Several implementations registered for one service type. All are kept. |
IEnumerable<T> injection |
a resolution style | Asking for the collection gives you every registered implementation. |
| Last-one-wins | a resolution rule | A single-service resolve returns the last registration. |
| Registration order | the order of your Add calls |
Determines the order in the injected IEnumerable<T>. |
GetServices<T>() |
a method | Resolves all implementations. The explicit form of IEnumerable<T>. |
TryAddEnumerable |
a method | Registers only if that exact service+implementation pair is absent. See 6.6. |
| Composite pattern | a design pattern | One implementation that wraps and delegates to a collection of others. |
| Chain of responsibility | a design pattern | Handlers offered an item in turn until one takes it. See 22.5. |
The concept¶
One interface, many implementations¶
Some jobs are naturally plural. Validating an order means running several rules. Notifying a customer might mean email and SMS and a push notification.
You could write one class containing all of them, but then adding a rule means editing that class. Instead, register each as its own implementation:
builder.Services.AddScoped<IOrderValidator, AmountValidator>();
builder.Services.AddScoped<IOrderValidator, StockValidator>();
builder.Services.AddScoped<IOrderValidator, CustomerCreditValidator>();
And ask for all of them:
public class OrderService(IEnumerable<IOrderValidator> validators)
{
public void Validate(Order order)
{
foreach (var validator in validators)
validator.Validate(order);
}
}
Adding a fourth rule is one registration line. OrderService never changes — which is the
open/closed principle in practice (22.1).
A picture: a panel of inspectors rather than one inspector with a long checklist. Hiring another inspector does not mean rewriting anyone's job description.
The two ways of asking¶
This is the part worth being precise about:
// Asking for ONE → the LAST registered
public class A(IOrderValidator validator) { } // CustomerCreditValidator
// Asking for ALL → every one, in registration order
public class B(IEnumerable<IOrderValidator> validators) { } // all three
⚠️ Last-one-wins for a single resolve is a deliberate feature — it is how you override a framework default — but it also means an accidental extra registration silently changes behaviour with no warning.
How it works¶
The simple version¶
builder.Services.AddScoped<INotificationChannel, EmailChannel>();
builder.Services.AddScoped<INotificationChannel, SmsChannel>();
builder.Services.AddScoped<INotificationChannel, PushChannel>();
public class NotificationService(
IEnumerable<INotificationChannel> channels,
ILogger<NotificationService> logger)
{
public async Task NotifyAsync(User user, string message, CancellationToken ct)
{
foreach (var channel in channels)
{
try
{
await channel.SendAsync(user, message, ct);
}
catch (Exception ex)
{
// One channel failing should not stop the others
logger.LogError(ex, "Channel {Channel} failed", channel.GetType().Name);
}
}
}
}
That try/catch inside the loop is a real design decision: if SMS is down, the email should still go. Letting the exception escape would abandon the remaining channels.
Resolving explicitly¶
var validators = provider.GetServices<IOrderValidator>(); // IEnumerable<T>
var last = provider.GetRequiredService<IOrderValidator>(); // just the last
GetServices<T>() returns an empty sequence if none are registered — it does not throw. That
makes "zero or more handlers" easy to express, and it also means a missing registration is
silent, which is occasionally a trap.
⚠️ TryAdd breaks this¶
// ✗ Only the first is ever registered
services.TryAddScoped<IOrderValidator, AmountValidator>();
services.TryAddScoped<IOrderValidator, StockValidator>(); // silently skipped
TryAdd checks whether the service type is registered, so after the first call it does
nothing. Use TryAddEnumerable when you want several but no duplicates
(6.6):
services.TryAddEnumerable(ServiceDescriptor.Scoped<IOrderValidator, AmountValidator>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<IOrderValidator, StockValidator>());
How it actually works — order matters¶
The IEnumerable<T> arrives in registration order, which matters when the handlers are not
independent:
// Cheap checks first — fail fast before hitting the database
builder.Services.AddScoped<IOrderValidator, AmountValidator>(); // in-memory
builder.Services.AddScoped<IOrderValidator, StockValidator>(); // DB query
builder.Services.AddScoped<IOrderValidator, CreditCheckValidator>(); // external API
If the amount is invalid, you never make the API call. That ordering is deliberate and invisible unless you know the rule.
⚠️ Relying on order is fragile though. Someone reorganising Program.cs can change behaviour
with no obvious signal. If order genuinely matters, make it explicit:
public interface IOrderValidator
{
int Order { get; }
void Validate(Order order);
}
// Then sort, rather than trusting registration order
foreach (var validator in validators.OrderBy(v => v.Order))
validator.Validate(order);
The deeper detail — the composite pattern¶
Injecting IEnumerable<T> everywhere spreads the looping logic around. An alternative is one
implementation that wraps the rest:
public class CompositeOrderValidator(IEnumerable<IOrderValidator> validators)
: IOrderValidator
{
public void Validate(Order order)
{
var errors = new List<string>();
foreach (var validator in validators)
{
try { validator.Validate(order); }
catch (ValidationException ex) { errors.Add(ex.Message); }
}
if (errors.Count > 0)
throw new ValidationException(errors); // report ALL failures, not just the first
}
}
Consumers then inject the plain interface and know nothing about there being several:
public class OrderService(IOrderValidator validator) // just one, apparently
{
public void Process(Order order) => validator.Validate(order);
}
⚠️ Registering that needs care, because the composite implements the same interface it consumes — register it as itself and expose it via a factory:
builder.Services.AddScoped<AmountValidator>();
builder.Services.AddScoped<StockValidator>();
builder.Services.AddScoped<IOrderValidator>(sp => new CompositeOrderValidator(
[
sp.GetRequiredService<AmountValidator>(),
sp.GetRequiredService<StockValidator>()
]));
Registering the composite as IOrderValidator and injecting IEnumerable<IOrderValidator>
into it would make it contain itself — infinite recursion and a stack overflow.
Collecting all errors rather than throwing on the first is the other real benefit of the composite. A user submitting a form wants every problem at once, not one per round trip. See 11.5.
Code¶
A realistic pipeline — several handlers, ordered, with one deliberately last:
builder.Services.AddScoped<IOrderEnricher, CustomerDetailsEnricher>();
builder.Services.AddScoped<IOrderEnricher, PricingEnricher>();
builder.Services.AddScoped<IOrderEnricher, ShippingEstimateEnricher>();
builder.Services.AddScoped<IOrderEnricher, AuditEnricher>(); // last on purpose
public class OrderQueryService(
IOrderRepository repo,
IEnumerable<IOrderEnricher> enrichers)
{
public async Task<Order> GetAsync(Guid id, CancellationToken ct)
{
var order = await repo.GetAsync(id, ct)
?? throw new NotFoundException(id);
// Runs in registration order, so audit sees the fully enriched order
foreach (var enricher in enrichers)
await enricher.EnrichAsync(order, ct);
return order;
}
}
Adding a fifth enricher is one line in Program.cs. Nothing else in the codebase changes —
that is the whole point of the pattern.
Choosing between one and many¶
| You want | Use |
|---|---|
| One implementation, swappable | A single registration |
| One of several, chosen by name | Keyed services (6.6) |
| One of several, chosen at runtime | A factory (6.8) |
| All of them, every time | IEnumerable<T> |
| All of them, hidden behind one interface | A composite |
Interview questions¶
Q: What happens if you register two implementations of the same interface?
Both stay in the container, because the service collection is genuinely a list rather than a
dictionary. Which you get depends on how you ask: resolving the interface directly gives you the
last one registered, while injecting IEnumerable<T> of that interface gives you all of them
in registration order. Last-one-wins is deliberate and useful for overriding a framework default,
but it also means an accidental duplicate registration silently changes which implementation
you get.
Q: When would you inject IEnumerable<T>?
When the job is naturally plural — running several validation rules, sending a notification through several channels, applying a set of enrichers. The benefit is that adding another implementation is a single registration line and the consuming class never changes, which is the open/closed principle in practice. I would also add a try/catch around each item where the handlers are independent, so one failing channel does not abandon the rest.
Q: Does the order of the injected collection matter?
It is registration order, and it often does matter — you typically want cheap in-memory checks
before ones that hit a database or an external API, so you fail fast. The risk is that it is
implicit: someone tidying Program.cs can change behaviour with no obvious signal. If the order
is genuinely significant I would make it explicit, either with an Order property on the
interface that you sort by, or by composing them deliberately rather than relying on the
container.
Q: What is the composite pattern here?
One implementation of the interface that takes the collection of all the others and delegates to them. Consumers then inject the plain interface and have no idea there are several, which keeps the looping logic in one place rather than spread across every consumer. It also lets you collect all the failures rather than throwing on the first, which is what you want for validation. The thing to be careful about is registration — the composite implements the interface it consumes, so registering it as that interface while also injecting the collection into it would make it contain itself and recurse infinitely.
Traps ⚠️¶
TryAddsilently skips all but the first implementation. UseTryAddEnumerable.- Last-one-wins for a single resolve means a duplicate registration changes behaviour with no warning.
GetServices<T>()returns empty rather than throwing when nothing is registered, so a missing registration is silent.- Registration order is implicit. Reordering
Program.cscan change behaviour. - A composite registered as the interface it consumes recurses infinitely.
- An exception in one handler abandons the rest unless you catch per item.
- Injecting both
TandIEnumerable<T>gives you the last one plus all of them — including that same instance twice, if lifetimes allow.
Related¶
- 6.6 Registration APIs —
TryAddEnumerableand keyed services - 6.8 Factories and open generics — runtime selection
- 6.2 The built-in container — why the collection is a list
- 11.7 FluentValidation — this pattern in a real library
- 22.1 SOLID — open/closed in practice
- 22.4 Composite pattern — the pattern itself
- 22.5 Chain of responsibility — the related one