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

📚 Interview question

How do you register services with the built-in .NET container? Explain AddSingleton, AddScoped and AddTransient, the TryAdd* methods and Replace, and what happens when you register several implementations of the same interface and inject IEnumerable<T>.

Covers registering services in IServiceCollection: lifetime methods, TryAdd, TryAddEnumerable and Replace, last-registration-wins resolution and injecting all implementations with IEnumerable<T>.

Junior Theory Beginner aspnet-core dependency-injection iservicecollection service-registration tryadd

🎯 Key points

  • IServiceCollection is a list of ServiceDescriptor (service type, implementation, lifetime, optional key since .NET 8)
  • Singleton for stateless thread-safe services and caches; scoped for DbContext and per-request state; transient for lightweight stateless helpers
  • Implementation can be a type, an instance or a factory delegate
  • Several registrations: injecting T gets the last one; IEnumerable<T> gets all, in registration order
  • TryAdd* only adds if the service type is not registered yet
  • TryAddEnumerable avoids adding the same implementation twice
  • Replace swaps the first registration for a service type; RemoveAll removes all
  • Registrations are frozen once Build() creates the provider

⏱ 30-second answer

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.

  • If you register the same service type several times, injecting 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Registration is simpler than it looks: builder.Services is an IServiceCollection, which is a list of ServiceDescriptor objects. Each descriptor says 'for service type X, use this implementation type, instance or factory, with this lifetime'. AddSingleton, AddScoped and AddTransient just append a descriptor. Nothing is resolved until builder.Build() turns the list into a ServiceProvider, and after that the list is read-only.

Because it's a list, duplicates are allowed. If I register IEmailSender twice, a constructor asking for IEmailSender gets the last one, and a constructor asking for IEnumerable<IEmailSender> gets both, in registration order. That second behaviour is great for pipelines of validators, health checks or notification channels. The TryAdd family exists for the opposite case: TryAddSingleton<IClock, SystemClock>() only adds if nobody registered IClock yet, so a library can supply a default the app can override by registering first. TryAddEnumerable is the variant for multi-registration, it skips the add if that exact implementation type is already there, so calling AddMyLibrary() twice doesn't double up handlers. And Replace swaps 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 AddSingleton after your registration and silently wins, or someone calls AddXxx() twice and every notification is sent twice. If order matters, I make it explicit with TryAdd, Replace or a test that asserts the resolved type."


The registration methods

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

Single vs many

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate understands what a registration really is and how duplicates and ordering behave, not just the three lifetime method names.

Green flags

  • Describes IServiceCollection as a list of descriptors
  • Knows last-wins for single resolution and all-in-order for IEnumerable<T>
  • Explains TryAdd vs TryAddEnumerable with a library example
  • Mentions the second-container problem with BuildServiceProvider()

Red flags

  • Thinks registering twice throws or that the first wins
  • Never heard of TryAdd
  • Uses Replace thinking it clears all registrations

📚 Learn in depth

1. What a registration is

IServiceCollection  (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.

2. How duplicates resolve

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]

3. The TryAdd family

  • 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.

4. Replace and RemoveAll

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.

5. After Build()

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).

Try it yourself

  1. Register two IGreeter implementations, inject IGreeter and IEnumerable<IGreeter> into an endpoint and print the types.
  2. Swap the order and observe which one wins.
  3. Replace one AddScoped with TryAddScoped and register it before and after the other; see when it is skipped.
  4. Call a helper that uses AddSingleton<INotificationChannel, SmsChannel>() twice, then switch it to TryAddEnumerable and count the instances.
  5. Write a test that builds the provider and asserts GetRequiredService<IGreeter>() is the expected type.

💻 Code

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>();

⚠ Common mistakes

  • Mistake: Assuming the first registration wins. Why it is wrong: single resolution uses the last descriptor. Instead: register overrides after defaults, or use TryAdd for defaults.
  • Mistake: Calling a shared 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.
  • Mistake: Using 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.
  • Mistake: Expecting Replace to remove every registration. Why it is wrong: it only removes the first match. Instead: RemoveAll<T>() then add.
  • Mistake: Registering a disposable object with 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).
  • Mistake: Choosing lifetimes by habit, for example registering a 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.
  • Mistake: Calling 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions injecting IEnumerable<T> to pick one implementation Why: Checks the candidate can turn multi-registration into a clean Strategy selection
    How to answer

    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.

    • In DI, register several implementations and inject IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.
    • For one small function with no dependencies, a 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.

  2. When: Candidate mentions choosing an implementation at run time Why: Checks factories, keyed services and avoiding the 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.

  3. When: Candidate wants to resolve a service during registration Why: Checks awareness of duplicate singleton containers and ASP0000
    How to answer

    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:

    • a factory delegate 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;
    • a hosted service or code after builder.Build() for start-up work.

    Trade-off: deferring moves failures from start-up to first use, so pair it with ValidateOnBuild.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me