skip to content

In ASP.NET Core, how do TryAddScoped, TryAddEnumerable, Replace and RemoveAll differ from a plain AddScoped, and why do library AddX methods use them?

level: middleimportance: should knowfreq 44%

answer

  1. namespace ...DependencyInjection.Extensions
  2. TryAdd checks the service type only
  3. TryAddEnumerable checks the implementation type too
  4. Replace removes the first match
  5. RemoveAll skips keyed descriptors

basics

~20 s

TryAddScoped adds only when the service type has no registration yet; TryAddEnumerable skips only an identical implementation type; Replace swaps the first matching registration; RemoveAll deletes every unkeyed one. Libraries use TryAdd so app registrations survive and AddX stays idempotent.

solid answer

~40 s

`AddScoped` always appends a descriptor. The other methods live in `Microsoft.Extensions.DependencyInjection.Extensions` and inspect the list first. `TryAddScoped<IFeeCalculator, StandardFeeCalculator>()` adds nothing if **any** registration for `IFeeCalculator` (with the same key) exists, so an app that registered its own calculator first keeps it. `TryAddEnumerable` is for services that are meant to have many implementations: it skips only when the same service type **and** the same implementation type are already registered, which makes calling `AddX()` twice harmless. `Replace` removes the **first** descriptor with that service type and key, then appends the new one. `RemoveAll<T>()` removes every unkeyed descriptor of `T`. ASP.NET Core does this itself: `AddProblemDetails()` calls `TryAddSingleton<IProblemDetailsService, ProblemDetailsService>()` and `TryAddEnumerable` for its `IProblemDetailsWriter`.

code

csharp · 13 lines
csharp
using Microsoft.Extensions.DependencyInjection.Extensions;

builder.Services.AddScoped<IFeeCalculator, StandardFeeCalculator>();
builder.Services.AddScoped<IFeeCalculator, HolidayFeeCalculator>();

// removes StandardFeeCalculator only, appends ArtisanFeeCalculator
builder.Services.Replace(
    ServiceDescriptor.Scoped<IFeeCalculator, ArtisanFeeCalculator>());
// list: HolidayFeeCalculator, ArtisanFeeCalculator

builder.Services.RemoveAll<IFeeCalculator>();
builder.Services.AddScoped<IFeeCalculator, ArtisanFeeCalculator>();
// list: ArtisanFeeCalculator

go deeper

for a junior

Recall that TryAdd adds only when nothing is registered for the service type, and that it lives in the Microsoft.Extensions.DependencyInjection.Extensions namespace.

for a middle

Explain the matching rule of each method: service type for TryAdd, service plus implementation type for TryAddEnumerable, first match for Replace, unkeyed only for RemoveAll.

for a senior

Design a library AddX() so applications can override its defaults and calling it twice is harmless, and explain the TryAddEnumerable exception with factory registrations.

for a principal

Weigh library-provided defaults against explicit application wiring, and decide where overriding with Replace is acceptable versus a sign the library should expose an option.

## Why plain Add is not enough for libraries `AddScoped`, `AddSingleton` and `AddTransient` always append a `ServiceDescriptor`. For application code that is fine, because the last registration wins. For a **library** that exposes an `AddX()` extension method it causes two problems: - if the application registered its own implementation **before** calling `AddX()`, the library's later registration overrides it; - if `AddX()` is called twice, by two modules or by mistake, every multi-implementation service gets duplicated and runs twice. The `TryAdd*` family, `Replace` and `RemoveAll` solve these. They are extension methods in the `Microsoft.Extensions.DependencyInjection.Extensions` namespace, which the Web SDK's implicit usings do not import, so a file that calls them needs its own `using`. ## The methods compared | Method | Checks | Effect | |---|---|---| | `AddScoped<TService, TImpl>()` | nothing | always appends | | `TryAddScoped<TService, TImpl>()` | service type and key | appends only if no descriptor for that service type exists | | `TryAddEnumerable(descriptor)` | service type, implementation type and key | appends unless that exact implementation is already registered | | `Replace(descriptor)` | service type and key | removes the **first** match, then appends | | `RemoveAll<T>()` | service type, unkeyed only | removes every unkeyed descriptor of `T` | | `RemoveAllKeyed<T>(key)` | service type and key | removes the keyed descriptors with that key | Each `TryAdd*` lifetime has a keyed twin, such as `TryAddKeyedScoped`. ## TryAdd: a default the application can override In the artisan marketplace, a shared payments library supplies a standard fee calculator: ```csharp using Microsoft.Extensions.DependencyInjection.Extensions; public static IServiceCollection AddMarketplacePayments(this IServiceCollection services) { services.TryAddScoped<IFeeCalculator, StandardFeeCalculator>(); services.TryAddEnumerable( ServiceDescriptor.Scoped<IPaymentWebhookHandler, RefundWebhookHandler>()); return services; } ``` If `Program.cs` registers `ArtisanFeeCalculator` **before** calling `AddMarketplacePayments()`, the `TryAddScoped` finds the existing descriptor and adds nothing. If the app registers its calculator **after**, plain last-wins already gives the app's version. Either way the application wins. ASP.NET Core uses the same pattern: `AddHttpContextAccessor()` is a single `TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>()`, and `AddProblemDetails()` uses `TryAddSingleton<IProblemDetailsService, ProblemDetailsService>()`. ## TryAddEnumerable: many implementations, no duplicates Some services are designed to be injected as `IEnumerable<T>`: webhook handlers, `IConfigureOptions<T>` setups, problem-details writers. `TryAddScoped` is wrong for them, because the second handler would be skipped. `TryAddEnumerable` compares the **implementation type** as well, so `RefundWebhookHandler` and `ChargebackWebhookHandler` both register, while a second call to `AddMarketplacePayments()` adds nothing new. MVC's `AddMvcCore()` registers its `IConfigureOptions<MvcOptions>` setup this way. Because it needs the implementation type, `TryAddEnumerable` throws `ArgumentException` ("Implementation type cannot be ... because it is indistinguishable from other services") when it cannot tell: a factory typed as `Func<IServiceProvider, IPaymentWebhookHandler>` reports the interface itself as its implementation type. Use the two-type form, `ServiceDescriptor.Scoped<IPaymentWebhookHandler, RefundWebhookHandler>(sp => ...)`. ## Replace and RemoveAll: overriding on purpose When an application must swap a registration that already exists: 1. `Replace(ServiceDescriptor.Scoped<IFeeCalculator, ArtisanFeeCalculator>())` removes the **first** descriptor for `IFeeCalculator` and appends the new one. With two earlier registrations, one survives, and `IEnumerable<IFeeCalculator>` still holds two items. 2. `RemoveAll<IFeeCalculator>()` followed by `AddScoped<IFeeCalculator, ArtisanFeeCalculator>()` leaves exactly one. `RemoveAll` ignores keyed descriptors; use `RemoveAllKeyed` for those. Both return the `IServiceCollection`, so they chain. ## Ordering pitfalls `TryAdd` is a check against the list **as it is at that moment**, so call order still matters: 1. An application registration made **after** a library's `TryAddScoped` is a plain second descriptor. Single resolves get the application's, but `IEnumerable<IFeeCalculator>` holds both, and code that loops over calculators runs the library default too. 2. A library that uses plain `AddScoped` cannot be overridden by registering first; the application must register after it, or use `Replace`. 3. `TryAdd` ignores lifetime. If the existing descriptor is a singleton and the library meant scoped, the singleton stays, with whatever captive-dependency consequences that has. 4. Keys count: `TryAddKeyedScoped<IFeeCalculator, StandardFeeCalculator>("eu")` is not blocked by an unkeyed `IFeeCalculator`, and `TryAddScoped` is not blocked by a keyed one, because the check compares the key too. The habit that avoids most surprises: libraries register defaults with `TryAdd*` and multi-implementation services with `TryAddEnumerable`, and applications override with an explicit `Replace` or `RemoveAll` plus `Add`, not by relying on call order. All of these methods must run before `builder.Build()`; after that the collection is read-only.

  • Why does TryAddEnumerable throw when given ServiceDescriptor.Scoped<IPaymentWebhookHandler>(sp => new RefundWebhookHandler())?
    It deduplicates on the implementation type, and a factory typed as `Func<IServiceProvider, IPaymentWebhookHandler>` reports the interface itself as its implementation type. Such a descriptor is indistinguishable from any other factory registration, so it throws `ArgumentException`. Use `ServiceDescriptor.Scoped<IPaymentWebhookHandler, RefundWebhookHandler>(sp => ...)` so the concrete type is known.
  • A library calls TryAddScoped for IFeeCalculator after your app registered one. Which does IEnumerable<IFeeCalculator> contain?
    Only yours. `TryAddScoped` found an existing descriptor for the service type and added nothing, so the collection holds a single `IFeeCalculator` registration. Had the library used `AddScoped`, the sequence would hold both and a single resolve would return the library's.

  • TryAddScoped skips only when the same implementation type is already registered.
  • Replace removes every existing registration of the service type.
  • RemoveAll<T>() also removes the keyed registrations of T.
  • TryAddScoped is the right call for webhook handlers meant to be injected as IEnumerable<T>.
  • TryAdd methods are available everywhere through the default implicit usings.