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

📚 Interview question

Show how you would use keyed services in .NET 10 to inject two differently configured implementations of the same interface, for example blob storage for invoices and for user uploads. Cover AddKeyedSingleton, [FromKeyedServices], IKeyedServiceProvider, [ServiceKey], KeyedService.AnyKey and what changed in .NET 10, and explain when a factory or strategy resolver is the better choice.

Keyed services in Microsoft.Extensions.DependencyInjection (.NET 8+, with .NET 10 changes): registering, injecting with [FromKeyedServices] in constructors and Minimal APIs, resolving through IKeyedServiceProvider, [ServiceKey], AnyKey fallbacks, and keyed services versus factories.

Mid-Level Coding Intermediate aspnet-core azure-blob-storage dependency-injection dotnet-10 keyed-services

🎯 Key points

  • Keyed services arrived in .NET 8 and are current in .NET 10: AddKeyedSingleton/Scoped/Transient register under any object key, matched with Equals/GetHashCode
  • Lifetimes apply per key: one keyed singleton per key, one keyed scoped instance per key per scope; choose them exactly as for unkeyed services
  • [FromKeyedServices("invoices")] on constructor, Minimal API and MVC action parameters; keyed and unkeyed registrations are separate
  • IKeyedServiceProvider.GetRequiredKeyedService belongs in factories or resolvers, not business classes
  • [ServiceKey] injects the resolution key; KeyedService.AnyKey registers a fallback for any key
  • .NET 10 breaking change: GetKeyedService(AnyKey) throws and GetKeyedServices(AnyKey) excludes AnyKey registrations, so code using AnyKey as a query must be updated
  • Parameterless [FromKeyedServices] (.NET 10) inherits the parent's key via ServiceKeyLookupMode.InheritKey
  • Use keys for a fixed set known at start-up; use a factory or strategy resolver when the choice depends on request data

⏱ 30-second answer

Keyed services (.NET 8+) let you register several implementations of one interface under an object key: AddKeyedSingleton<IDocumentStore, BlobDocumentStore>("invoices", ...). Consumers ask for one with [FromKeyedServices("invoices")] on a constructor or endpoint parameter, or resolve it through IKeyedServiceProvider.GetRequiredKeyedService. A service can receive its own key with [ServiceKey], and KeyedService.AnyKey registers a fallback for any key. In .NET 10, querying with AnyKey changed (GetKeyedService(AnyKey) throws) and a parameterless [FromKeyedServices] inherits the parent's key. Keys suit a small, fixed set known at start-up; when the choice depends on request data, a factory or strategy resolver keeps the decision testable and stops keys spreading through the code like a service locator.

🗣 Full answer (senior)

How I would answer this in an interview

"Keyed services, added in .NET 8, are the built-in container's answer to named registrations. You register IDocumentStore twice with AddKeyedSingleton, once under \"invoices\" and once under \"uploads\", each with a factory that builds a BlobContainerClient for its own container. A consumer that always needs the invoice store says so with [FromKeyedServices(\"invoices\")] on its constructor parameter, and Minimal API handlers and MVC actions accept the same attribute. Keyed and unkeyed registrations live side by side: a plain IDocumentStore request won't see the keyed ones.

There are a few extra tools. [ServiceKey] on a constructor parameter gives an implementation the key it was resolved with, so one class can serve many keys. KeyedService.AnyKey registers a fallback that answers for any key. And in .NET 10 two things changed: asking for GetKeyedService(KeyedService.AnyKey) now throws because AnyKey is a registration wildcard, not a query, and GetKeyedServices(AnyKey) no longer returns the AnyKey registrations. .NET 10 also lets a parameterless [FromKeyedServices] inherit the key of the service being built, which is handy for keyed decorators.

The mistake I see is using keys for decisions made from request data, like picking a payment gateway per order, by injecting IKeyedServiceProvider everywhere. That's a service locator with strings. Keys are for a fixed set wired at start-up. When the choice depends on data, I write a small resolver that owns the mapping and can be unit-tested."


The API surface

API Purpose
AddKeyedSingleton/Scoped/Transient<TService, TImpl>(key) Register under a key (any object, compared with Equals)
AddKeyedSingleton<T>(key, (sp, key) => ...) Factory receives the provider and the key
[FromKeyedServices(key)] Inject by key in constructors, Minimal APIs, MVC actions, SignalR hubs
[FromKeyedServices] (no key, .NET 10) ServiceKeyLookupMode.InheritKey: use the key the parent was resolved with
IKeyedServiceProvider.GetRequiredKeyedService<T>(key) Resolve by key in code (factories, resolvers)
GetKeyedServices<T>(key) All registrations for that key
[ServiceKey] Inject the resolution key into the implementation
KeyedService.AnyKey Register a fallback for any key

Keys vs alternatives

Approach Choice made Good for Weakness
Keyed services At composition (attribute) Fixed variants: storage containers, regional clients Strings or enums leak into constructors
IEnumerable<T> + resolver At run time from data Strategy per order, tenant, country Extra class; must handle "not found"
Factory delegate Func<string, T> At run time Small cases Hidden logic in Program.cs; hard to discover
Separate interfaces (IInvoiceStore) Compile time Two variants with different meaning More types

Production example

On an [invoicing platform] we replaced two marker interfaces and a hand-rolled StoreFactory switch with keyed registrations for three blob containers. Each store kept its own retry and timeout settings, cold-start resolution stayed under a millisecond, and the PR removed about 120 lines. We kept a resolver for the per-customer archive tier, because that choice came from customer data, not from wiring.

🔍 What the interviewer is checking

Checks whether the candidate can use the .NET 8+ keyed services API correctly, knows the .NET 10 changes, and can tell wiring decisions from run-time business decisions.

Green flags

  • Shows AddKeyed*, [FromKeyedServices] and a factory that receives the key
  • Knows keyed and unkeyed registrations are separate and keys use Equals
  • Mentions [ServiceKey], AnyKey and the .NET 10 AnyKey query change
  • Uses a resolver for data-driven choices and avoids the service locator

Red flags

  • Injects IServiceProvider and switches on strings in business code
  • Doesn't know keyed services exist and builds a dictionary of Func<T>
  • Uses string literals everywhere with no validation

📚 Learn in depth

1. How keyed services are stored

Since .NET 8, ServiceDescriptor has ServiceKey, IsKeyedService, KeyedImplementationType, KeyedImplementationFactory and KeyedImplementationInstance. Internally the container identifies a service by a ServiceIdentifier = (service key, service type). Unkeyed services use a null key, which is why keyed and unkeyed registrations don't mix.

ServiceIdentifier("invoices", IDocumentStore) -> factory A (Singleton)
ServiceIdentifier("uploads",  IDocumentStore) -> factory B (Singleton)
ServiceIdentifier(null,       IDocumentStore) -> not registered

Call sites are cached per identifier, so keyed resolution is as fast as unkeyed once compiled.

2. Keys and equality

The key is an object and lookups use Equals/GetHashCode. Strings are case-sensitive, so "Invoices" and "invoices" are different keys. Enums and static readonly string constants avoid typos. Records work as composite keys.

3. Injection paths

Constructor      -> CallSiteFactory sees [FromKeyedServices] on the parameter
Minimal API      -> RequestDelegateFactory / RDG binds the parameter from the request's scope
MVC action       -> FromKeyedServices acts as a binding source
Code             -> IKeyedServiceProvider (the root and scoped providers implement it)

In .NET 10, FromKeyedServicesAttribute has a LookupMode: ExplicitKey (a key was passed), NullKey (null was passed) and InheritKey (no key: use the key of the service being constructed). InheritKey lets a keyed decorator ask for "the inner service with my key" without hard-coding it.

4. AnyKey and [ServiceKey]

Registering under KeyedService.AnyKey makes the registration match any key that has no exact registration. Combined with [ServiceKey], one class can serve many keys:

AddKeyedSingleton<IDocumentStore>(KeyedService.AnyKey, (sp, key) => new BlobDocumentStore((string)key!, ...))
GetRequiredKeyedService<IDocumentStore>("contracts") -> AnyKey factory with key = "contracts"

The .NET 10 breaking change: GetKeyedService(KeyedService.AnyKey) throws InvalidOperationException, and GetKeyedServices(KeyedService.AnyKey) no longer includes AnyKey registrations. Code that used AnyKey as a query ("give me everything") must enumerate specific keys.

5. Lifetimes and disposal

Lifetimes work as normal and per key: a keyed singleton is one instance per key; a keyed scoped service is one per key per scope. Disposal follows the same rules as unkeyed services. A factory that returns an object the container didn't create still gets it tracked for disposal if it implements IDisposable.

6. Third-party containers

Keyed services are part of Microsoft.Extensions.DependencyInjection.Abstractions, so container adapters must implement IKeyedServiceProvider and the IServiceProviderIsKeyedService check. Autofac and others added support; older adapters may throw. Check before relying on keys in a library.

Try it yourself

  1. Register two keyed IDocumentStores and an unkeyed request for IDocumentStore; confirm the unkeyed request fails with ValidateOnBuild on.
  2. Register an AnyKey factory with [ServiceKey] and resolve three different keys; check you get three singletons.
  3. On .NET 10, call GetKeyedService<IDocumentStore>(KeyedService.AnyKey) and observe the exception.
  4. Write a keyed decorator using a parameterless [FromKeyedServices] and check it receives the inner service for the same key.
  5. Benchmark keyed vs unkeyed resolution with BenchmarkDotNet; they should be within noise.

💻 Code

Keyed blob stores, injection by key, AnyKey with [ServiceKey], and a resolver for data-driven choices (.NET 10, Azure.Storage.Blobs, Azure.Identity):

using Azure.Identity;
using Azure.Storage.Blobs;
using Microsoft.Extensions.DependencyInjection;

namespace Invoicing.Storage;

public static class StoreKeys
{
    public const string Invoices = "invoices"; // constants: no typo-driven failures
    public const string Uploads = "uploads";
}

public interface IDocumentStore
{
    Task UploadAsync(string name, Stream content, CancellationToken ct);
}

public sealed class BlobDocumentStore(BlobContainerClient container) : IDocumentStore
{
    public Task UploadAsync(string name, Stream content, CancellationToken ct) =>
        container.GetBlobClient(name).UploadAsync(content, overwrite: false, ct);
}

public sealed class InvoiceService([FromKeyedServices(StoreKeys.Invoices)] IDocumentStore store)
{
    public Task SaveAsync(Guid id, Stream pdf, CancellationToken ct) =>
        store.UploadAsync($"{id:N}.pdf", pdf, ct);
}

public static class StorageRegistration
{
    public static IServiceCollection AddDocumentStores(this IServiceCollection services, Uri accountUri)
    {
        services.AddSingleton(new BlobServiceClient(accountUri, new DefaultAzureCredential()));

        // One keyed singleton per container; the factory receives the key.
        foreach (var key in new[] { StoreKeys.Invoices, StoreKeys.Uploads })
        {
            services.AddKeyedSingleton<IDocumentStore>(key, (sp, k) =>
                new BlobDocumentStore(sp.GetRequiredService<BlobServiceClient>()
                    .GetBlobContainerClient((string)k!)));
        }
        services.AddScoped<InvoiceService>();
        return services;
    }
}

Minimal API injection, and a resolver when the key comes from request data:

app.MapPost("/uploads/{name}", async (
    string name,
    HttpRequest request,
    [FromKeyedServices(StoreKeys.Uploads)] IDocumentStore store,
    CancellationToken ct) =>
{
    await store.UploadAsync(name, request.Body, ct);
    return Results.Accepted();
});

// Data-driven choice: keep the mapping in one testable class, not in every caller.
public sealed class ArchiveStoreResolver(IKeyedServiceProvider provider)
{
    private static readonly HashSet<string> Allowed = ["hot", "cool", "archive"];

    public IDocumentStore For(string tier) =>
        Allowed.Contains(tier)
            ? provider.GetRequiredKeyedService<IDocumentStore>(tier)
            : throw new ArgumentOutOfRangeException(nameof(tier), tier, "Unknown storage tier.");
}

⚠ Common mistakes

  • Mistake: Using string literals for keys in many places. Why it is wrong: keys are case-sensitive objects; one typo fails only at resolution. Instead: use constants or an enum, and turn on ValidateOnBuild.
  • Mistake: Injecting IKeyedServiceProvider into business classes to pick a service per request. Why it is wrong: it is the service locator anti-pattern; dependencies become invisible and tests need a container. Instead: inject the specific keyed service, or one resolver that owns the mapping.
  • Mistake: Expecting an unkeyed IDocumentStore request to return a keyed registration. Why it is wrong: keyed and unkeyed services have different identifiers. Instead: register an unkeyed default explicitly if you need one.
  • Mistake: Upgrading from .NET 8 or 9 to .NET 10 without searching for KeyedService.AnyKey used as a query. Why it is wrong: this is a documented breaking change: GetKeyedService(KeyedService.AnyKey) now throws InvalidOperationException, and GetKeyedServices(KeyedService.AnyKey) no longer returns services registered under AnyKey, so a "list every store" health check or admin screen silently returns fewer items. Instead: grep for AnyKey in resolution calls before upgrading, enumerate the known keys explicitly, and cover it with a test.
  • Mistake: Using keys where two separate interfaces would say more. Why it is wrong: [FromKeyedServices("x")] IStore hides meaning that IInvoiceArchive would make explicit. Instead: use keys for interchangeable variants, interfaces for different roles.
  • Mistake: Giving a keyed service a different lifetime from what the unkeyed version would need. Why it is wrong: a keyed scoped DbContext captured by a keyed singleton is still a captive dependency. Instead: choose keyed lifetimes with the same rules: thread-safe and stateless → singleton, per-request state → scoped, cheap and stateful per use → transient.
  • Mistake: Assuming every third-party container supports keyed services. Why it is wrong: adapters must implement IKeyedServiceProvider; older ones throw. Instead: check the adapter version before using keys in shared libraries.
  • Mistake: Giving an AnyKey factory unbounded keys from user input. Why it is wrong: each key creates and caches a new singleton, so memory grows with every distinct value. Instead: validate keys against a known set first.

🏛 Senior insight: trade-offs

Keyed services removed most of the reasons teams brought in Autofac for named registrations. The judgement is where the decision lives: if the variant is fixed by wiring ("invoice service always uses the invoice container"), a key on the constructor is honest and cheap. If it depends on data ("this customer's tier"), the decision is business logic and belongs in a resolver you can unit-test. Watch for keys turning into stringly-typed configuration scattered across constructors.

Option When it fits Cost When not to
Keyed service + attribute Fixed variants known at start-up Key coupling in constructors Choice depends on request data
Resolver over IKeyedServiceProvider or IEnumerable<T> Data-driven choice One extra class Only one or two fixed variants
Separate interfaces Variants have different meaning More types Truly interchangeable variants
AnyKey + [ServiceKey] Many keys, same implementation Unbounded singletons if keys aren't validated Keys from user input

Measure memory if you use AnyKey singletons: each distinct key is cached for the life of the root provider.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions picking an implementation per order or customer Why: Checks run-time selection with factories, keyed services and IEnumerable resolvers without a service locator
    How to 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.

  2. When: Candidate mentions factories or run-time values Why: Checks factory delegates, Func<T>, Lazy<T> and ActivatorUtilities as alternatives
    How to answer

    When the container can't build something up front, inject a factory instead of the object.

    • A factory registration (AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.
    • Unlike Autofac, the built-in container (still true in .NET 10) does not auto-supply Func<T> or Lazy<T>; you register them explicitly.
    • For run-time values, define a small typed factory interface and implement it with ActivatorUtilities.CreateFactory (the generic ObjectFactory<T> overload arrived in .NET 8), which mixes your argument with container services and caches the reflection.

    The key rule: anything a factory creates is owned by the caller, who must dispose it. The trade-off is flexibility against hidden lifetimes: factories are the main way captive and leaked dependencies sneak in.

  3. When: Candidate injects IKeyedServiceProvider or IServiceProvider into business classes Why: Checks whether they recognise the service locator anti-pattern
    How to answer

    A service locator is when a class pulls its dependencies from a container (IServiceProvider.GetRequiredService<T>(), or a static ServiceLocator.Get<T>()) instead of declaring them in its constructor. It is harmful because it hides dependencies (the signature lies), moves missing-registration errors to run time on whatever code path hits them (and ValidateOnBuild can't see them), makes unit tests need a container, and invites lifetime bugs: resolving from the root in a singleton leaks transients or captures scoped services.

    It is acceptable at the composition boundary: Program.cs, factory delegates (sp => ...), IServiceScopeFactory in a BackgroundService, framework-style code like middleware or a message dispatcher choosing a handler by type. The test: is this infrastructure wiring, or business logic asking for things?

🛠 Real-world problems: how you handle them

AnyKey store created a singleton per customer and leaked memory
Situation
A [document-management] API on .NET [10] in Azure App Service [Australia East] registered `IDocumentStore` under `KeyedService.AnyKey`, using `[ServiceKey]` as the blob container name. A new endpoint passed the customer id from the route straight in as the key. About [8,000] customers used it daily.
Signals
Working set grew about [150] MB a day until App Service recycled the instance; dotnet-counters showed Gen 2 size climbing steadily and no drop after full GCs. Application Insights showed rising response times late each day.
Investigation
Took two `dotnet-gcdump` snapshots six hours apart and compared them in Visual Studio: thousands of `BlobDocumentStore` and `BlobContainerClient` instances rooted by the root `ServiceProviderEngineScope`'s realised-services dictionary. Traced the keys back to the new endpoint through code search for `GetRequiredKeyedService`.
Resolution
Mitigation: scaled out and set a scheduled restart while fixing. Fix: replaced the per-customer key with a single keyed store per tier and passed the customer id as a blob path prefix; added an allow-list check in the resolver so unknown keys throw.
Prevention
A code-review rule that keys never come from user input; an integration test that resolves 1,000 random keys and asserts it fails; a memory alert on Gen 2 growth per instance; a short ADR on when to use keyed services.

How to tell it (STAR)

**S:** On [our document API], memory grew around [150] MB a day until App Service recycled the instance. **T:** I was asked to find the leak before a [customer onboarding] that would double traffic. **A:** I took two gcdumps hours apart and saw thousands of blob store objects held by the root DI scope. We'd registered the store under AnyKey, and a new endpoint passed the customer id as the key, so every customer got a new cached singleton. I changed it to one store per tier with the customer id as a path prefix, made the resolver reject unknown keys, and added a test and a review rule that keys never come from user input. **R:** Memory flattened at around [400] MB, the daily recycles stopped, and the onboarding went ahead on the same instance count.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me