Covers registering services in IServiceCollection: lifetime methods, TryAdd, TryAddEnumerable and Replace, last-registration-wins resolution and injecting all implementations with IEnumerable<T>.
IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.
T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.Replace swaps the first registration; RemoveAll clears them.The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.
"Registration is simpler than it looks:
builder.Servicesis anIServiceCollection, which is a list ofServiceDescriptorobjects. Each descriptor says 'for service type X, use this implementation type, instance or factory, with this lifetime'.AddSingleton,AddScopedandAddTransientjust append a descriptor. Nothing is resolved untilbuilder.Build()turns the list into aServiceProvider, and after that the list is read-only.Because it's a list, duplicates are allowed. If I register
IEmailSendertwice, a constructor asking forIEmailSendergets the last one, and a constructor asking forIEnumerable<IEmailSender>gets both, in registration order. That second behaviour is great for pipelines of validators, health checks or notification channels. TheTryAddfamily exists for the opposite case:TryAddSingleton<IClock, SystemClock>()only adds if nobody registeredIClockyet, so a library can supply a default the app can override by registering first.TryAddEnumerableis the variant for multi-registration, it skips the add if that exact implementation type is already there, so callingAddMyLibrary()twice doesn't double up handlers. AndReplaceswaps the first registration of a service type, which is handy in tests.The mistake I see is relying on order without realising it: a library calls
AddSingletonafter your registration and silently wins, or someone callsAddXxx()twice and every notification is sent twice. If order matters, I make it explicit withTryAdd,Replaceor a test that asserts the resolved type."
| Method | What it does | Typical use |
|---|---|---|
AddSingleton<TService, TImpl>() |
One instance for the app's lifetime | Stateless, thread-safe services, caches |
AddScoped<TService, TImpl>() |
One instance per scope (per HTTP request) | DbContext, unit-of-work services |
AddTransient<TService, TImpl>() |
New instance every resolution | Lightweight, stateless helpers |
AddSingleton<T>(instance) |
Registers an existing object | Pre-built config objects (the container won't dispose it) |
AddScoped<T>(sp => ...) |
Factory delegate | Construction needing logic or config |
TryAdd{Lifetime} |
Adds only if service type not registered | Library defaults |
TryAddEnumerable(descriptor) |
Adds only if this implementation not already registered for the service | Library plug-ins, handlers |
Replace(descriptor) |
Removes the first matching registration, adds the new one | Tests, overriding a library |
RemoveAll<T>() |
Removes all registrations for T |
Tests |
| You inject | You get |
|---|---|
IEmailSender |
The last registered implementation |
IEnumerable<IEmailSender> |
All implementations, in registration order (empty if none) |
IEmailSender? with no registration |
Resolution fails; optional dependencies need GetService in a factory or a null object |
A notification service registered EmailChannel, SmsChannel and PushChannel as INotificationChannel and injected IEnumerable<INotificationChannel>. After a refactor a shared AddNotifications() was called from two modules and every customer got two SMS messages. Switching to TryAddEnumerable and adding a test that asserts exactly three channels fixed it permanently.
Checks the candidate understands what a registration really is and how duplicates and ordering behave, not just the three lifetime method names.
Green flags
IServiceCollection as a list of descriptorsIEnumerable<T>TryAdd vs TryAddEnumerable with a library exampleBuildServiceProvider()Red flags
TryAddReplace thinking it clears all registrationsIServiceCollection (List<ServiceDescriptor>)
├─ { ServiceType: IClock, Impl: SystemClock, Lifetime: Singleton }
├─ { ServiceType: IEmailSender, Impl: SmtpSender, Lifetime: Scoped }
├─ { ServiceType: IEmailSender, Impl: SendGridSender, Lifetime: Scoped }
└─ { ServiceType: AppDbContext, Factory: sp => ..., Lifetime: Scoped }
A ServiceDescriptor has exactly one of ImplementationType, ImplementationInstance or ImplementationFactory. In .NET 8+ it also has an optional ServiceKey for keyed services.
When Build() runs, the provider groups descriptors by service type. For a single resolution it uses the last descriptor in the group; for IEnumerable<T> it builds all of them in order. So registration order is semantic.
Resolve IEmailSender → SendGridSender (last)
Resolve IEnumerable<IEmailSender> → [SmtpSender, SendGridSender]
TryAdd(descriptor): skip if any descriptor for that service type exists.TryAddEnumerable(descriptor): skip if a descriptor with the same service type and implementation type exists. It throws if the implementation type can't be determined (for example a factory returning the interface type), because it can't compare.This is how framework methods like AddLogging() or AddHttpClient() stay idempotent: call them ten times, register once.
Replace removes the first descriptor with that service type and appends the new one. If there were several, the others remain. In tests prefer RemoveAll<T>() then Add... to be explicit.
The collection is marked read-only once the host is built; adding afterwards throws. If you call BuildServiceProvider() yourself in Program.cs you create a second container with its own singletons, which is a common bug (analyser ASP0000 warns about it).
IGreeter implementations, inject IGreeter and IEnumerable<IGreeter> into an endpoint and print the types.AddScoped with TryAddScoped and register it before and after the other; see when it is skipped.AddSingleton<INotificationChannel, SmsChannel>() twice, then switch it to TryAddEnumerable and count the instances.GetRequiredService<IGreeter>() is the expected type.Registration patterns and how duplicates resolve.
using Microsoft.Extensions.DependencyInjection.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Lifetimes
builder.Services.AddSingleton(TimeProvider.System); // instance: not disposed by the container
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddTransient<IPriceFormatter, AudPriceFormatter>();
// Several implementations: TryAddEnumerable keeps AddNotifications() idempotent.
builder.Services.AddNotifications();
builder.Services.AddNotifications(); // second call adds nothing
var app = builder.Build();
app.MapPost("/notify", async (string message, IEnumerable<INotificationChannel> channels, CancellationToken ct) =>
{
foreach (var channel in channels) // Email, then Sms: registration order
await channel.SendAsync(message, ct);
return TypedResults.Accepted((string?)null);
});
app.Run();
public interface INotificationChannel { Task SendAsync(string message, CancellationToken ct); }
public sealed class EmailChannel : INotificationChannel { public Task SendAsync(string m, CancellationToken ct) => Task.CompletedTask; }
public sealed class SmsChannel : INotificationChannel { public Task SendAsync(string m, CancellationToken ct) => Task.CompletedTask; }
public interface IOrderRepository;
public sealed class SqlOrderRepository : IOrderRepository;
public interface IPriceFormatter;
public sealed class AudPriceFormatter : IPriceFormatter;
public static class NotificationRegistration
{
public static IServiceCollection AddNotifications(this IServiceCollection services)
{
// Adds each implementation once, however often this is called.
services.TryAddEnumerable(ServiceDescriptor.Scoped<INotificationChannel, EmailChannel>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<INotificationChannel, SmsChannel>());
return services;
}
}
// In a test: replace a registration explicitly.
services.RemoveAll<IOrderRepository>();
services.AddScoped<IOrderRepository, InMemoryOrderRepository>();
TryAdd for defaults.AddXxx() from several modules with plain Add* for multi-implementation services. Why it is wrong: each call appends again, so handlers run twice. Instead: use TryAddEnumerable for plug-in style registrations.TryAddEnumerable with a factory that returns the interface type. Why it is wrong: it can't determine the implementation type and throws. Instead: use a typed factory overload or ServiceDescriptor.Describe with a concrete type.Replace to remove every registration. Why it is wrong: it only removes the first match. Instead: RemoveAll<T>() then add.AddSingleton(instance) and expecting the container to dispose it. Why it is wrong: the container only disposes objects it created itself; an instance you passed in is yours. Instead: register the implementation type or a factory delegate (AddSingleton<IFoo>(sp => new Foo(...))) so the container owns and disposes it, and keep AddSingleton(instance) for non-disposable objects or ones whose disposal you explicitly handle (for example in IHostApplicationLifetime.ApplicationStopped).DbContext-using repository as singleton. Why it is wrong: a singleton captures the scoped DbContext (a captive dependency) and shares it across concurrent requests. Instead: match the lifetime to state: scoped for anything that holds a DbContext or per-request data, singleton only for thread-safe, stateless or cache-like services.services.BuildServiceProvider() in Program.cs to resolve something early. Why it is wrong: it creates a second container with duplicate singletons (ASP0000). Instead: use options, IConfigureOptions<T> or a factory delegate.Registration order is an invisible API. The senior move is to make intent explicit: TryAdd for defaults you expect to be overridden, TryAddEnumerable for plug-ins, and a small test that builds the real composition root and asserts the critical resolutions. That test catches double registrations and silent overrides before production.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Add* |
App-level registrations in the composition root | None | In library code meant to be overridable |
TryAdd* |
Library or shared-module defaults | Override must be registered earlier | When you must guarantee your implementation |
TryAddEnumerable |
Multi-implementation plug-ins | Needs a determinable implementation type | Single-implementation services |
Replace / RemoveAll |
Tests, deliberately overriding a library | Easy to hide intent | Production code where order can change |
Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).
.NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.
IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.Func<T, TResult> delegate is a strategy without the ceremony.The trade-off: more types and indirection, so a short, stable switch is often clearer.
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.
services.BuildServiceProvider() takes a snapshot of the IServiceCollection and builds a second, independent root container. It has its own singleton cache, so every singleton resolved from it is a different instance from the app's (two caches, two connection pools); nothing disposes it, so its singletons and root-resolved disposables leak; registrations added later are missing; and scoped services resolved from its root effectively live for ever. The ASP0000 analyser warns about it.
Instead, defer the work until the real container exists:
sp => new Foo(sp.GetRequiredService<IBar>()), which runs on first resolution from the real provider;IConfigureOptions<T> (or AddOptions<T>().Configure<IDep>(...)) for options that need services;builder.Build() for start-up work.Trade-off: deferring moves failures from start-up to first use, so pair it with ValidateOnBuild.
Last updated 23 Nov 2026.