Run-time implementation selection in .NET 10 DI: keyed services (AddKeyedScoped, [FromKeyedServices], GetRequiredKeyedService), Func factory delegates, an IEnumerable-to-FrozenDictionary resolver, unknown-key handling, testing, and keeping IServiceProvider at the composition root.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.
"I'd model each provider as an implementation of one interface,
IPaymentGateway, which is the Strategy pattern, and then the question is only how to pick one. If the choice is fixed per call site, for example the refund endpoint always uses Stripe, I use keyed services from .NET 8. I registerAddKeyedScoped<IPaymentGateway, StripeGateway>("stripe")and inject with[FromKeyedServices("stripe")]on the constructor parameter or the minimal API parameter. That's clean and visible, but the key has to be a constant.Here the choice depends on the order, so I need a run-time resolver. My default is an
IPaymentGatewayResolverwith one method,Resolve(string provider). There are two good implementations. The first takesIEnumerable<IPaymentGateway>, where each gateway exposes itsProvidername, and builds aFrozenDictionarywith a case-insensitive comparer. It never touches the container, but it constructs every gateway on every scope. That's fine for three cheap gateways, but not if one opens connections in its constructor. The second lives in the composition root and callsGetRequiredKeyedService<IPaymentGateway>(provider), so only the chosen gateway is built. Either way, an unknown provider becomes a domain error such asUnknownPaymentProviderExceptionor a 422, not a rawInvalidOperationException, and I validate the configured provider names at startup withValidateOnStart.The mistake I see is injecting
IServiceProviderinto the checkout service and callingGetServicewith a string built from the order. That's a service locator: the dependency is invisible, tests have to build a container, and a typo fails at checkout instead of at startup. Business code should ask for 'a gateway for this provider', not for the container."
| Approach | Key known | Constructs | Container in business code | Best for |
|---|---|---|---|---|
[FromKeyedServices("stripe")] |
Compile time | Only the keyed one | No | Fixed call sites |
IEnumerable<T> β dictionary resolver |
Run time | All implementations | No | Few, cheap implementations |
Typed resolver over GetRequiredKeyedService |
Run time | Only the chosen one | No (resolver is infrastructure) | Expensive or many implementations |
Func<string, IPaymentGateway> delegate |
Run time | Only the chosen one | No | Small apps; less discoverable |
IServiceProvider.GetService in the service |
Run time | Chosen one | Yes (anti-pattern) | Never |
| Source of key | Failure mode | Handling |
|---|---|---|
| Configuration | Typo in appsettings |
Validate at startup with ValidateOnStart |
| Request/order data | Customer or upstream sends unknown provider | Domain error β 422 ProblemDetails |
| Code constant | Missing registration | ValidateOnBuild catches missing keyed registrations |
A retail checkout used serviceProvider.GetService(Type.GetType($"Payments.{provider}Gateway")). A renamed class broke Afterpay payments for 40 minutes on a sale day, because nothing failed until a customer chose that option. Replacing it with keyed registrations, a typed resolver and a startup check that every configured provider resolves meant the next rename failed the deployment pipeline instead.
Checks practical DI skills in .NET 8+ and whether the candidate can choose implementations at run time without falling into the service locator anti-pattern.
Green flags
IEnumerable construction cost.Red flags
IServiceProvider into business services.Type.GetType on strings from requests.CheckoutService βββΆ IPaymentGatewayResolver.Resolve(order.Provider)
β
βΌ
Β«interfaceΒ» IPaymentGateway
β² β² β²
StripeGateway PayPalGateway BankTransferGateway
The resolver is the only place that knows how keys map to implementations.
.NET 8 added ServiceDescriptor.ServiceKey. Registrations such as AddKeyedScoped<TService, TImpl>(object? key) store the key; resolution matches on (serviceType, key). You resolve with:
[FromKeyedServices(key)] on a constructor parameter or minimal API/MVC action parameter;IServiceProvider.GetRequiredKeyedService<T>(key) / GetKeyedService<T>(key);IKeyedServiceProvider directly.KeyedService.AnyKey registers a fallback that matches any key, and an implementation can receive its own key with [ServiceKey] on a constructor parameter. Keys are compared with object.Equals, so "stripe" and "Stripe" are different keys; normalise them.
IEnumerable<T>Resolving IEnumerable<IPaymentGateway> builds every registered implementation for that scope, along with their dependency graphs. If BankTransferGateway creates an SftpClient in its constructor, every checkout pays for it. Keep gateway constructors cheap, or use the keyed approach.
| Property | Constructor injection / typed resolver | Service locator |
|---|---|---|
| Dependencies visible | Yes, in the constructor | No, hidden in method bodies |
| Missing registration found | At startup (ValidateOnBuild) |
At run time, on that code path |
| Unit test setup | Pass fakes | Build or mock a container |
| Refactoring safety | Compiler helps | String keys and reflection |
The resolver uses the container, but only in the infrastructure layer, behind an interface the domain owns. That keeps the container dependency in one replaceable place.
If gateways are scoped (they use a scoped DbContext for idempotency keys), the resolver must be scoped too. A singleton resolver holding IServiceProvider from the root would resolve scoped gateways from the root, which throws with ValidateScopes, or worse, captures them silently.
Adding Afterpay means a new AfterpayGateway class and one AddKeyedScoped line. CheckoutService and the resolver don't change. That's the same Open/Closed benefit as a Strategy, with DI doing the selection.
Console.WriteLine in each gateway constructor; compare how many run per request.CheckoutService using a fake IPaymentGatewayResolver, with no container.KeyedService.AnyKey fallback that throws a clear error, and test an unknown key.Gateways, both resolvers, and the registrations:
namespace Payments;
using System.Collections.Frozen;
public sealed record Charge(Guid OrderId, decimal Amount, string Currency);
public sealed record PaymentResult(bool Succeeded, string? Reference, string? Error);
public interface IPaymentGateway
{
string Provider { get; }
Task<PaymentResult> ChargeAsync(Charge charge, CancellationToken ct);
}
public sealed class StripeGateway(HttpClient http) : IPaymentGateway
{
public string Provider => "stripe";
public async Task<PaymentResult> ChargeAsync(Charge charge, CancellationToken ct)
{
using HttpResponseMessage res = await http.PostAsJsonAsync("/v1/charges", charge, ct);
return res.IsSuccessStatusCode ? new(true, res.Headers.ETag?.Tag, null) : new(false, null, res.ReasonPhrase);
}
}
public sealed class UnknownPaymentProviderException(string provider)
: Exception($"No payment gateway is configured for '{provider}'.")
{
public string Provider { get; } = provider;
}
public interface IPaymentGatewayResolver
{
IPaymentGateway Resolve(string provider);
}
// Option A: no container access; builds every gateway in the scope
public sealed class EnumerableGatewayResolver(IEnumerable<IPaymentGateway> gateways) : IPaymentGatewayResolver
{
private readonly FrozenDictionary<string, IPaymentGateway> _byProvider =
gateways.ToFrozenDictionary(g => g.Provider, StringComparer.OrdinalIgnoreCase);
public IPaymentGateway Resolve(string provider) =>
_byProvider.TryGetValue(provider, out IPaymentGateway? g) ? g : throw new UnknownPaymentProviderException(provider);
}
// Option B: lives in the composition root; builds only the chosen gateway
public sealed class KeyedGatewayResolver(IServiceProvider services) : IPaymentGatewayResolver
{
public IPaymentGateway Resolve(string provider) =>
services.GetKeyedService<IPaymentGateway>(provider.ToLowerInvariant()) // keys compared with Equals
?? throw new UnknownPaymentProviderException(provider);
}
// Business code depends on the narrow resolver, never on IServiceProvider
public sealed class CheckoutService(IPaymentGatewayResolver gateways)
{
public Task<PaymentResult> PayAsync(Order order, CancellationToken ct) =>
gateways.Resolve(order.PaymentProvider).ChargeAsync(new Charge(order.Id, order.Total, "AUD"), ct);
}
// Program.cs
builder.Services.AddHttpClient<StripeGateway>(c => c.BaseAddress = new Uri("https://api.stripe.com"));
builder.Services.AddKeyedScoped<IPaymentGateway>("stripe", (sp, _) => sp.GetRequiredService<StripeGateway>());
builder.Services.AddKeyedScoped<IPaymentGateway, PayPalGateway>("paypal");
builder.Services.AddScoped<IPaymentGatewayResolver, KeyedGatewayResolver>();
builder.Services.AddScoped<CheckoutService>();
// Fixed call site: the key is a constant, so inject it directly
app.MapPost("/refunds/stripe", ([FromKeyedServices("stripe")] IPaymentGateway gateway, RefundRequest req, CancellationToken ct)
=> gateway.ChargeAsync(new Charge(req.OrderId, -req.Amount, "AUD"), ct));
// Test: no container needed
[Fact]
public async Task Uses_the_gateway_for_the_order_provider()
{
var fake = new FakeGateway("paypal");
var sut = new CheckoutService(new EnumerableGatewayResolver([fake]));
await sut.PayAsync(new Order { PaymentProvider = "PayPal", Total = 10m }, CancellationToken.None);
Assert.Single(fake.Charges);
}
IServiceProvider into CheckoutService and calling GetService with a computed type or key. Why it is wrong: That is a service locator; dependencies are hidden, tests need a container, and typos fail at checkout. Instead: Depend on a narrow IPaymentGatewayResolver.[FromKeyedServices] with a key from request data. Why it is wrong: Attribute keys must be compile-time constants; it can't express a run-time choice. Instead: Use a resolver for run-time keys and keyed injection only for fixed call sites.switch over provider names inside the checkout service. Why it is wrong: Every new provider edits the service, and the switch grows with each provider's setup. Instead: One class per provider plus registration (Open/Closed).IEnumerable<IPaymentGateway> when gateways are expensive to construct. Why it is wrong: All gateways and their dependency graphs are built on every request. Instead: Keep constructors cheap or use the keyed resolver.InvalidOperationException from GetRequiredKeyedService bubble out as a 500. Why it is wrong: An unknown provider is a client or configuration error, not a server crash. Instead: Map it to a domain error (422) and validate configured keys at startup."Stripe" vs "stripe"). Why it is wrong: Keys use object.Equals, so lookups fail. Instead: Normalise keys or use constants.I treat "select an implementation at run time" as Strategy + Factory and keep the selection logic in one place behind a domain-owned interface. Keyed services made this much cleaner in .NET 8, but they are a container feature, not a design. Business code still shouldn't know keys exist.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
[FromKeyedServices] |
Call site always wants one implementation | String key in attribute | Run-time choice |
IEnumerable<T> resolver |
2β5 cheap implementations, want zero container coupling | Constructs all | Expensive constructors |
| Keyed resolver | Many or expensive implementations | Container used in one class | Tiny apps where IEnumerable is simpler |
| Config-driven registration | Choice per environment/tenant at startup | Restart to change | Per-request choice |
I measure two things: startup validation coverage (every configured key resolves in a test) and allocation per request when using the IEnumerable approach (BenchmarkDotNet or dotnet-counters allocation rate), so the convenience doesn't quietly cost latency.
The Open/Closed Principle says modules should be open for extension but closed for modification: you add new behaviour by adding code, not by editing tested code. In C# this usually means a strategy interface with one implementation per variant, registered in DI, so adding a new payment method is a new class rather than another case in a growing switch. I apply it where change actually happens repeatedly. A small, stable switch (or a switch expression over a closed set) is fine; building extension points for variants that never arrive is speculative generality.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
How to tell it (STAR)
**S:** During a [sale day] at [company], Afterpay checkouts started failing right after a release, while other payment methods were fine. **T:** I had to restore payments fast and make sure a rename could never break checkout again. **A:** The trace showed the gateway lookup returning null. The code built a type name from the provider string and asked the container for it, and a cleanup had renamed the class. I rolled back within [12 minutes], then replaced the reflection with keyed registrations and a small typed resolver, and added a startup test that resolves every configured provider. **R:** We lost about [N] orders during the incident. Over the next [six months], two further renames failed the pipeline instead of production, and we've had [zero] gateway-lookup incidents since.
Last updated 18 Nov 2026.