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.
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.
"Keyed services, added in .NET 8, are the built-in container's answer to named registrations. You register
IDocumentStoretwice withAddKeyedSingleton, once under\"invoices\"and once under\"uploads\", each with a factory that builds aBlobContainerClientfor 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 plainIDocumentStorerequest 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.AnyKeyregisters a fallback that answers for any key. And in .NET 10 two things changed: asking forGetKeyedService(KeyedService.AnyKey)now throws because AnyKey is a registration wildcard, not a query, andGetKeyedServices(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
IKeyedServiceProvidereverywhere. 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."
| 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 |
| 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 |
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.
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
AddKeyed*, [FromKeyedServices] and a factory that receives the keyEquals[ServiceKey], AnyKey and the .NET 10 AnyKey query changeRed flags
IServiceProvider and switches on strings in business codeFunc<T>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.
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.
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.
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.
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.
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.
IDocumentStores and an unkeyed request for IDocumentStore; confirm the unkeyed request fails with ValidateOnBuild on.[ServiceKey] and resolve three different keys; check you get three singletons.GetKeyedService<IDocumentStore>(KeyedService.AnyKey) and observe the exception.[FromKeyedServices] and check it receives the inner service for the same key.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.");
}
ValidateOnBuild.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.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.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.[FromKeyedServices("x")] IStore hides meaning that IInvoiceArchive would make explicit. Instead: use keys for interchangeable variants, interfaces for different roles.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.IKeyedServiceProvider; older ones throw. Instead: check the adapter version before using keys in shared libraries.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.
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.
When the container can't build something up front, inject a factory instead of the object.
AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.Func<T> or Lazy<T>; you register them explicitly.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.
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?
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.
Last updated 23 Nov 2026.