6.6 — Add vs TryAdd vs TryAddEnumerable, and Keyed Services¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.5 Scopes · Next: 6.7 Multiple implementations
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Add always appends. TryAdd only registers if nothing is there already. That difference
matters most when writing libraries.
Add— always adds. Duplicates are allowed, and the last one wins on a single resolve.TryAdd— adds only if the service type is unregistered. Lets consumers override your default.AddKeyedSingleton(.NET 8+) — register several implementations under names, and ask for one by name.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
Add{Lifetime} |
a method | Always appends a registration. Duplicates allowed. |
TryAdd{Lifetime} |
a method | Appends only if that service type has no registration yet. |
TryAddEnumerable |
a method | Appends only if that exact service + implementation pair is absent. |
Replace |
a method | Removes existing registrations for a type and adds a new one. |
RemoveAll<T> |
a method | Removes every registration for a service type. |
| Last-one-wins | a resolution rule | Resolving a single service gives the last registered implementation. |
| Keyed service | a registration (.NET 8+) | Registered under a key, so several implementations coexist by name. |
[FromKeyedServices] |
an attribute | Marks a constructor parameter to be resolved by key. |
GetRequiredKeyedService<T>(key) |
a method | Resolve a keyed service explicitly. |
| Default registration | a library pattern | A sensible implementation a library registers, expecting consumers may replace it. |
The concept¶
The problem TryAdd solves¶
builder.Services is genuinely a list (6.2), so Add appends
rather than replaces:
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IEmailSender, SendGridEmailSender>();
// Resolving IEmailSender → SendGridEmailSender (the LAST one)
// Resolving IEnumerable<IEmailSender> → BOTH
For your own application that is usually fine, and occasionally useful for deliberately overriding a framework default.
It becomes a real problem in libraries. Consider a library that registers a default:
// The consumer wants their own
builder.Services.AddSingleton<IClock, TestClock>();
builder.Services.AddSomeLibrary(); // ⚠️ registered AFTER, so it wins
The consumer's deliberate choice is silently overridden, because the library ran last.
TryAdd fixes it:
// Inside the library
services.TryAddSingleton<IClock, SystemClock>(); // only if nobody registered one
Now the library provides a default without stomping on a caller's choice, regardless of call order.
A picture: Add is writing your name on the sign-up sheet. TryAdd is writing it only if
the sheet is blank — you will take the job if nobody else has it, but you will not push someone
else off.
How it works¶
The simple version¶
using Microsoft.Extensions.DependencyInjection.Extensions; // ← TryAdd lives here
services.TryAddSingleton<IClock, SystemClock>();
services.TryAddScoped<IOrderRepository, EfOrderRepository>();
services.TryAddTransient<IEmailFormatter, EmailFormatter>();
⚠️ TryAdd requires a separate using. The methods are in
Microsoft.Extensions.DependencyInjection.Extensions, not the main namespace, so they will not
appear in IntelliSense until you add it. That trips people up.
| Method | Adds when |
|---|---|
Add |
Always |
TryAdd |
The service type has no registration |
TryAddEnumerable |
That exact service + implementation pair is absent |
TryAddEnumerable — for collections¶
TryAdd is wrong when you deliberately want several implementations
(6.7), because after the first registration it does nothing.
// ✗ Only the first is ever added
services.TryAddScoped<IValidator, EmailValidator>();
services.TryAddScoped<IValidator, PhoneValidator>(); // silently skipped
TryAddEnumerable compares the pair, so different implementations all register while
duplicates of the same one do not:
services.TryAddEnumerable(ServiceDescriptor.Scoped<IValidator, EmailValidator>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<IValidator, PhoneValidator>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<IValidator, EmailValidator>()); // skipped
// Resolving IEnumerable<IValidator> → EmailValidator, PhoneValidator
That is the point: an extension method called twice by accident does not double up. This is
how the framework registers things like IConfigureOptions<T>.
Replacing a registration¶
When you genuinely want to swap something out:
// Replace in one call
services.Replace(ServiceDescriptor.Scoped<IEmailSender, FakeEmailSender>());
// Or remove then add
services.RemoveAll<IEmailSender>();
services.AddScoped<IEmailSender, FakeEmailSender>();
⚠️ Replace only replaces the first matching descriptor, so with several registrations for
one type you may not get what you expect. RemoveAll followed by Add is unambiguous.
This is exactly what integration tests do to swap real dependencies for fakes — 20.7.
How it actually works — keyed services (.NET 8+)¶
Before .NET 8, registering two implementations of one interface and choosing between them meant a factory or a marker interface. Keyed services made it first-class:
builder.Services.AddKeyedSingleton<IStorage, AzureBlobStorage>("azure");
builder.Services.AddKeyedSingleton<IStorage, S3Storage>("s3");
builder.Services.AddKeyedSingleton<IStorage, LocalStorage>("local");
Resolve by key in a constructor:
public class BackupService(
[FromKeyedServices("azure")] IStorage primary,
[FromKeyedServices("s3")] IStorage secondary)
{
// Two different implementations of the same interface
}
Or explicitly from the provider:
Keys can be any object, so an enum is often cleaner than a string:
public enum StorageKind { Azure, S3, Local }
builder.Services.AddKeyedSingleton<IStorage, AzureBlobStorage>(StorageKind.Azure);
public class BackupService([FromKeyedServices(StorageKind.Azure)] IStorage storage) { }
⚠️ Keyed and non-keyed registrations are separate. Registering only keyed services means
GetRequiredService<IStorage>() — without a key — throws. If you want both, register a default
too:
builder.Services.AddKeyedSingleton<IStorage, AzureBlobStorage>("azure");
builder.Services.AddSingleton<IStorage, AzureBlobStorage>(); // the default
The deeper detail — keyed vs a factory¶
Keyed services are not always the answer. Two alternatives:
A factory, when the choice depends on runtime data:
Keys are fixed at registration time. If the decision depends on the current tenant or user, a factory is more appropriate.
Configuration-driven selection, when there is genuinely only one at runtime:
builder.Services.AddSingleton<IStorage>(sp =>
{
var config = sp.GetRequiredService<IConfiguration>();
return config["Storage:Provider"] switch
{
"azure" => new AzureBlobStorage(...),
"s3" => new S3Storage(...),
_ => new LocalStorage(...)
};
});
If the app uses one storage provider chosen by configuration, this is simpler than keys — the
consuming code just asks for IStorage and does not need to know which it got.
Keyed services earn their place when several implementations are used simultaneously — a primary and a secondary backup target, or a read and a write connection.
Code¶
A realistic library registration extension, using the right method for each case:
public static class PaymentModuleExtensions
{
public static IServiceCollection AddPaymentModule(
this IServiceCollection services,
IConfiguration config)
{
// TryAdd — a sensible default the consumer may override
services.TryAddSingleton<IClock, SystemClock>();
// TryAddEnumerable — several handlers, and safe if called twice
services.TryAddEnumerable(
ServiceDescriptor.Scoped<IPaymentValidator, AmountValidator>());
services.TryAddEnumerable(
ServiceDescriptor.Scoped<IPaymentValidator, CurrencyValidator>());
// Keyed — both gateways are used at once, so both must be reachable
services.AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe");
services.AddKeyedScoped<IPaymentGateway, PayPalGateway>("paypal");
// Add — our own type, no override expected
services.AddScoped<IPaymentService, PaymentService>();
services.Configure<PaymentOptions>(config.GetSection("Payments"));
return services;
}
}
public class PaymentService(
[FromKeyedServices("stripe")] IPaymentGateway stripe,
[FromKeyedServices("paypal")] IPaymentGateway paypal,
IEnumerable<IPaymentValidator> validators) // all of them — see 6.7
{
public async Task<Receipt> PayAsync(Payment payment, CancellationToken ct)
{
foreach (var validator in validators)
validator.Validate(payment);
var gateway = payment.Method == PaymentMethod.PayPal ? paypal : stripe;
return await gateway.ChargeAsync(payment, ct);
}
}
Note the three different registration styles serving three different intents: a replaceable default, a collection of handlers, and named alternatives used side by side.
Interview questions¶
Q: What is the difference between Add and TryAdd?
Add always appends a registration, so calling it twice for the same interface leaves both in
the list and a single resolve gives you the last one. TryAdd only registers if that service
type has no registration at all. The distinction matters most in library code — a library
registering a default with Add will silently override a consumer's deliberate choice if it
happens to run afterwards, whereas TryAdd provides the default without stomping on anyone.
Worth knowing that TryAdd lives in a separate namespace, Microsoft.Extensions.DependencyInjection.Extensions,
so it does not appear in IntelliSense until you add that using.
Q: When would you use TryAddEnumerable?
When you deliberately want several implementations of one interface and want to avoid accidental
duplicates. TryAdd is wrong there, because after the first registration it does nothing — so a
second, different implementation is silently skipped. TryAddEnumerable compares the service and
implementation pair, so different implementations all register while a repeat of the same one is
ignored. That makes a registration extension safe to call twice, which is how the framework
registers things like options configuration.
Q: What are keyed services?
A .NET 8 feature letting you register several implementations of one interface under different
keys and ask for a specific one — either with [FromKeyedServices("name")] on a constructor
parameter or GetRequiredKeyedService on the provider. Before that you needed a factory or
marker interfaces. The thing to watch is that keyed and non-keyed registrations are separate, so
registering only keyed implementations means a plain GetRequiredService for that type throws.
Q: When would you use a factory instead of keyed services?
When the choice depends on runtime data rather than being fixed at registration. Keys are decided when you wire the container, so if the implementation depends on the current tenant or user, a factory that takes that value is more appropriate. And if the application genuinely uses only one implementation, selected by configuration, a factory registration with a switch is simpler than keys — consuming code just asks for the interface without needing to know which one it got. Keyed services earn their place when several implementations are genuinely used at the same time.
Traps ⚠️¶
TryAddneedsusing Microsoft.Extensions.DependencyInjection.Extensions. It will not appear in IntelliSense otherwise.TryAddwith multiple implementations silently skips all but the first. UseTryAddEnumerable.Addtwice means last-one-wins for a single resolve, with no warning.Replaceonly replaces the first matching descriptor. UseRemoveAllthenAddwhen there could be several.- Keyed and non-keyed registrations are separate. Keyed-only means a plain resolve throws.
- Keys are fixed at registration time. Runtime-dependent selection needs a factory.
- A library using
Addfor defaults overrides consumer choices depending on call order.
Related¶
- 6.2 The built-in container — why the collection is a list
- 6.7 Multiple implementations —
IEnumerable<T>injection - 6.8 Factories and open generics — the alternative to keys
- 6.11 Third-party containers — Scrutor's decoration
- 20.7 Integration testing — replacing registrations
- 1.26 Modern C# — keyed services in .NET 8