📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

You have several payment gateways (Stripe, PayPal, a bank API) and the right one depends on the order. Show how you would select the implementation at run time in ASP.NET Core using DI: factory delegates, keyed services with [FromKeyedServices], and an IEnumerable-based resolver. How do you avoid the service locator anti-pattern?

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.

Mid-Level Coding Intermediate aspnet-core dependency-injection design-patterns factory-method keyed-services strategy

🎯 Key points

  • Keyed services (introduced in .NET 8, unchanged in .NET 10): AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe") and [FromKeyedServices("stripe")] on constructor or minimal API parameters for keys known at compile time
  • Run-time key from data: a typed resolver (IPaymentGatewayResolver.Resolve(provider)), not IServiceProvider in business code
  • IEnumerable<IPaymentGateway> with a Provider property, turned into a FrozenDictionary with OrdinalIgnoreCase, gives a locator-free resolver; but it constructs every gateway
  • GetKeyedService/GetRequiredKeyedService<T>(key) inside a resolver at the composition root constructs only the chosen one; map unknown keys to a domain error instead of InvalidOperationException
  • Func<string, IPaymentGateway> registered as a factory delegate is concise but less discoverable and harder to mock than a named interface
  • Lifetimes: the resolver must not outlive the gateways (scoped resolver for scoped gateways)
  • Validate configured provider keys at startup (ValidateOnStart) so a typo fails deploy, not checkout
  • This is Strategy selected by a factory; adding a provider = new class + one registration (Open/Closed)

⏱ 30-second answer

This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:

  • Keyed services (.NET 8+): 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.
  • Typed resolver over keyed services: 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 register AddKeyedScoped<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 IPaymentGatewayResolver with one method, Resolve(string provider). There are two good implementations. The first takes IEnumerable<IPaymentGateway>, where each gateway exposes its Provider name, and builds a FrozenDictionary with 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 calls GetRequiredKeyedService<IPaymentGateway>(provider), so only the chosen gateway is built. Either way, an unknown provider becomes a domain error such as UnknownPaymentProviderException or a 422, not a raw InvalidOperationException, and I validate the configured provider names at startup with ValidateOnStart.

The mistake I see is injecting IServiceProvider into the checkout service and calling GetService with 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."


Options compared

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

Error handling for unknown keys

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Recognises Strategy + Factory.
  • Uses keyed services correctly and knows the compile-time-key limitation.
  • Writes a typed resolver and explains the IEnumerable construction cost.
  • Handles unknown keys and lifetimes deliberately.

Red flags

  • Injects IServiceProvider into business services.
  • Uses reflection or Type.GetType on strings from requests.
  • One big switch inside the service.

πŸ“š Learn in depth

1. Structure: Strategy plus a factory

CheckoutService ──▢ IPaymentGatewayResolver.Resolve(order.Provider)
                              β”‚
                              β–Ό
                     Β«interfaceΒ» IPaymentGateway
                    β–²          β–²             β–²
           StripeGateway  PayPalGateway  BankTransferGateway

The resolver is the only place that knows how keys map to implementations.

2. How keyed services work

.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.

3. The cost of 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.

4. Service locator: why it hurts

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.

5. Lifetimes

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.

6. Open/Closed in practice

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.

Try it yourself

  1. Implement both resolvers and add a Console.WriteLine in each gateway constructor; compare how many run per request.
  2. Write an xUnit test for CheckoutService using a fake IPaymentGatewayResolver, with no container.
  3. Add a startup check that resolves every provider listed in configuration and fails if one is missing.
  4. Register a KeyedService.AnyKey fallback that throws a clear error, and test an unknown key.

πŸ’» Code

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);
}

⚠ Common mistakes

  • Mistake: Injecting 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.
  • Mistake: Using [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.
  • Mistake: Building a giant 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).
  • Mistake: Resolving 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.
  • Mistake: Letting 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.
  • Mistake: Registering the resolver as a singleton over scoped gateways. Why it is wrong: It resolves from the root provider, which captures or fails for scoped services. Instead: Match lifetimes: scoped resolver for scoped gateways.
  • Mistake: Inconsistent key casing ("Stripe" vs "stripe"). Why it is wrong: Keys use object.Equals, so lookups fail. Instead: Normalise keys or use constants.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says adding a provider only needs a new class and a registration Why: Checks Open/Closed applied without speculative plug-in frameworks
    How to answer

    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.

  2. When: Candidate registers the resolver or gateways with different lifetimes Why: Checks lifetime mismatches between resolver and implementations
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Reflection-based gateway lookup broke Afterpay on a sale day
Situation
An e-commerce checkout on .NET [10] handling [~15,000] orders an hour during a [Click Frenzy] sale. The payment service picked a gateway with `serviceProvider.GetService(Type.GetType($"Payments.{provider}Gateway"))`.
Signals
Afterpay checkout failures jumped to [100%] after a deploy; Application Insights showed `NullReferenceException` in `CheckoutService.PayAsync`; payments dashboard showed Afterpay revenue at zero while other providers were normal.
Investigation
The exception's stack pointed to the `GetService` call returning null. A diff of the release showed `AfterpayGateway` had been renamed to `AfterpayV2Gateway` during a cleanup. Nothing referenced the type directly, so the compiler, `ValidateOnBuild` and unit tests couldn't catch it.
Resolution
Immediate: rolled back the deploy ([12 minutes] to recover). Real fix: replaced reflection with keyed registrations (`AddKeyedScoped<IPaymentGateway, AfterpayGateway>("afterpay")`), introduced `IPaymentGatewayResolver`, and mapped unknown providers to a 422 with a clear message.
Prevention
A startup check and an integration test resolve every provider listed in configuration; `ValidateOnBuild` on in CI; a code-review rule banning `IServiceProvider` and `Type.GetType` in application services; a synthetic checkout test per provider after each deploy.

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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me