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

📚 Interview question

Your app needs different implementations or settings depending on a name, the environment or configuration: two HttpClients for different partners, two sets of options for the same class, and a fake email sender in Development. How do you do named and conditional registration in .NET? Cover named and typed HttpClients, named options, registering by environment or configuration, and when the choice has to move to run time.

Named and conditional registration in .NET: named and typed HttpClients through IHttpClientFactory, named options with IOptionsMonitor.Get and IOptionsSnapshot.Get, registering implementations by environment or configuration in the composition root, and moving decisions to run time with feature flags or resolvers.

Intermediate Theory Intermediate aspnet-core conditional-registration dependency-injection ihttpclientfactory named-options

🎯 Key points

  • Named HttpClients: AddHttpClient("name", ...) then IHttpClientFactory.CreateClient("name"); an unknown name returns an unconfigured client
  • Typed clients: AddHttpClient<TClient>() registers TClient as transient with its own configured HttpClient
  • Named options: Configure<T>(name, section) read with IOptionsMonitor<T>.Get(name) or IOptionsSnapshot<T>.Get(name); IOptions<T>.Value is always the default (unnamed) instance, still true in .NET 10
  • Keyed services (.NET 8+) are the general-purpose named registration for any service type
  • Conditional registration happens once in the composition root using builder.Environment or builder.Configuration
  • Registration-time choices need a restart to change; run-time choices need a factory, resolver or feature flag
  • Per-tenant or per-customer variation scales through one resolver plus tenant-keyed options, not a registration per tenant
  • Avoid scattering IsDevelopment checks through classes; decide in Program.cs and test each environment's wiring

⏱ 30-second answer

The built-in container has no general "named" registration, so .NET gives you names in three places. Named HttpClients (AddHttpClient("partnerA", ...) + IHttpClientFactory.CreateClient("partnerA")) and typed clients give each partner its own base address, headers and handlers. Named options (Configure<SmtpOptions>("marketing", section)) are read with IOptionsMonitor<T>.Get(name) or IOptionsSnapshot<T>.Get(name). For any other type, keyed services are the named registration. Conditional registration is plain C# in the composition root: if (builder.Environment.IsDevelopment()) AddSingleton<IEmailSender, FakeEmailSender>(), or a branch on a configuration value. The trade-off: registration-time choices are simple and fast but fixed until restart; if it must change while running (feature flags, per tenant), move the choice into a factory or resolver.

🗣 Full answer (senior)

How I would answer this in an interview

"The built-in container doesn't have named registrations in general, but the parts of .NET that need names have their own mechanism. For HTTP, AddHttpClient(\"auspost\", c => c.BaseAddress = ...) registers a named configuration, and IHttpClientFactory.CreateClient(\"auspost\") gives you a client built from it with pooled handlers. I usually prefer a typed client, AddHttpClient<AusPostClient>(), because the consumer just injects AusPostClient. For settings, named options let the same class carry two configurations: Configure<SmtpOptions>(\"transactional\", ...) and Configure<SmtpOptions>(\"marketing\", ...), read with IOptionsMonitor<SmtpOptions>.Get(name). Plain IOptions<T> only knows the default, unnamed instance. For arbitrary services, keyed services since .NET 8 are the general answer.

Conditional registration is just C# in Program.cs. builder.Environment and builder.Configuration are available before Build(), so I can register a FakeEmailSender in Development, or pick AzureBlobStore versus LocalFileStore from a Storage:Provider setting. That decision happens once, at start-up.

The mistake I see is forgetting that last part. People register by configuration and then expect flipping the App Configuration value to switch implementations live. It won't until the app restarts. If the choice has to change at run time, I register both implementations and put a small resolver in front that reads IOptionsMonitor or a feature flag per call. The other mistake is a typo in a named client: CreateClient with an unknown name quietly returns an unconfigured client, and you find out when requests go to a relative URL and fail."


Where names live in .NET

Need Mechanism Read with
Several HTTP configurations Named client AddHttpClient("x") IHttpClientFactory.CreateClient("x")
A class per remote API Typed client AddHttpClient<TClient>() Inject TClient
Same options class, several configs Configure<T>("name", ...) / AddOptions<T>("name") IOptionsMonitor<T>.Get("name"), IOptionsSnapshot<T>.Get("name")
Several implementations of any service Keyed services (.NET 8+) [FromKeyedServices("name")]

Registration time vs run time

Decide at registration when Decide at run time when
It depends on the environment (Development fakes) It's a feature flag rolled out gradually
It's an infrastructure choice per deployment (blob vs local disk) It depends on the tenant, customer or request
A restart to change it is acceptable You need to switch without redeploying

Production example

In a [logistics] API we called three carriers through typed clients, each with its own base address, timeout and AddStandardResilienceHandler() settings. Moving from one shared HttpClient with per-call URLs to typed clients cut carrier-related 5xx errors from about 1.2% to 0.3%, mostly because each carrier got its own timeout instead of a shared 100-second default.

🔍 What the interviewer is checking

Checks whether the candidate knows the .NET mechanisms that provide names (HttpClient factory, named options, keyed services) and understands that registration-time decisions are fixed after Build().

Green flags

  • Uses typed or named clients and explains the unknown-name trap
  • Knows IOptions<T> gives only the default name
  • Decides environment and config choices in the composition root
  • Moves run-time choices into a resolver or feature flag

Red flags

  • Calls IsDevelopment() inside business classes
  • Expects a config change to swap registrations live
  • Creates new HttpClient() per partner

📚 Learn in depth

1. Named HttpClients under the hood

AddHttpClient("name", configure) doesn't register an HttpClient in the container. It registers named HttpClientFactoryOptions (named options!) holding the configuration actions and handler pipeline. CreateClient(name) looks up those options, takes a pooled HttpMessageHandler chain for that name (rotated every HandlerLifetime, 2 minutes by default, so DNS changes are picked up), and wraps it in a new HttpClient.

CreateClient("auspost")
   -> IOptionsMonitor<HttpClientFactoryOptions>.Get("auspost")
   -> handler pool["auspost"] (expires after HandlerLifetime)
   -> new HttpClient(handler, disposeHandler: false) + BaseAddress, headers

Because options return a default instance for an unknown name, CreateClient("auspots") gives a plain client with no base address. That's why typed clients or name constants are safer.

2. Typed clients

AddHttpClient<AusPostClient>() registers AusPostClient as transient and builds it with ITypedHttpClientFactory<T>, passing in a client named after the type. Injecting a typed client into a singleton captures one HttpClient and its handler forever, which defeats handler rotation. Use typed clients from transient or scoped consumers, or use IHttpClientFactory in singletons.

3. Named options

Every options registration has a name; the default is Options.DefaultName (empty string). IOptions<T>.Value returns only the default name. IOptionsMonitor<T>.Get(name) caches per name and is updated on reload; IOptionsSnapshot<T>.Get(name) is recomputed per scope. ConfigureAll<T> applies to every name, and IConfigureNamedOptions<T> lets a configure class handle names itself.

4. Conditional registration in the composition root

WebApplication.CreateBuilder(args)
   -> Configuration and Environment ready
   -> your registrations (can read both)
   -> builder.Build()  // container is fixed from here

Anything you branch on before Build() is a start-up decision. TryAdd* gives a third style: a library registers a default with TryAddSingleton, and the app's earlier registration wins. Replace/RemoveAll let tests or environments swap a registration.

5. Moving the decision to run time

Register both implementations (as keyed services or concrete types), and a resolver that chooses per call:

IEmailSender (resolver)
   -> IFeatureManager.IsEnabledAsync("UseNewProvider") ?
        keyed "sendgrid" : keyed "smtp"

Microsoft.FeatureManagement with Azure App Configuration gives percentage rollouts and targeting. The cost is one extra indirection and a per-call check.

Try it yourself

  1. Register a named client, call CreateClient with a misspelt name and inspect BaseAddress.
  2. Register two named SmtpOptions and print IOptions<SmtpOptions>.Value versus IOptionsMonitor<SmtpOptions>.Get("marketing").
  3. Register a fake sender only in Development and write a WebApplicationFactory test that asserts which implementation resolves in each environment.
  4. Inject a typed client into a singleton, change the DNS entry in your hosts file and watch requests keep going to the old address.
  5. Add a feature-flag resolver and flip the flag in appsettings.json with reloadOnChange to see it switch without a restart.

💻 Code

Named and typed clients, named options, environment- and configuration-based registration, and a run-time switch (.NET 10):

using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Typed clients: each carrier gets its own base address, timeout and resilience pipeline.
builder.Services.AddHttpClient<AusPostClient>(c =>
{
    c.BaseAddress = new Uri(builder.Configuration["Carriers:AusPost:BaseUrl"]!);
    c.Timeout = TimeSpan.FromSeconds(10);
}).AddStandardResilienceHandler();

// Named options: the same class, two configurations.
builder.Services.Configure<SmtpOptions>("transactional", builder.Configuration.GetSection("Smtp:Transactional"));
builder.Services.Configure<SmtpOptions>("marketing", builder.Configuration.GetSection("Smtp:Marketing"));

// Conditional registration: decided once, at start-up.
if (builder.Environment.IsDevelopment())
    builder.Services.AddSingleton<IEmailSender, FakeEmailSender>();
else
    builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();

// Configuration-based choice: also fixed until restart.
if (builder.Configuration["Storage:Provider"] == "Local")
    builder.Services.AddSingleton<IFileStore, LocalFileStore>();
else
    builder.Services.AddSingleton<IFileStore, BlobFileStore>();

var app = builder.Build();
app.Run();

public sealed class SmtpOptions
{
    public required string Host { get; init; }
    public int Port { get; init; } = 587;
}

public interface IEmailSender { Task SendAsync(string to, string body, CancellationToken ct); }
public interface IFileStore;
public sealed class LocalFileStore : IFileStore;
public sealed class BlobFileStore : IFileStore;

public sealed class AusPostClient(HttpClient http)
{
    public Task<string> GetRateAsync(string postcode, CancellationToken ct) =>
        http.GetStringAsync($"rates/{postcode}", ct);
}

public sealed class FakeEmailSender(ILogger<FakeEmailSender> log) : IEmailSender
{
    public Task SendAsync(string to, string body, CancellationToken ct)
    {
        log.LogInformation("Fake email to {To}", to);
        return Task.CompletedTask;
    }
}

// Reads the named options per send, so a config reload is picked up without restart.
public sealed class SmtpEmailSender(IOptionsMonitor<SmtpOptions> options) : IEmailSender
{
    public Task SendAsync(string to, string body, CancellationToken ct)
    {
        var smtp = options.Get("transactional");
        // ... connect to smtp.Host:smtp.Port and send
        return Task.CompletedTask;
    }
}

⚠ Common mistakes

  • Mistake: Using a string literal name with CreateClient in several places. Why it is wrong: an unknown name silently returns an unconfigured client, so requests go to a relative URL and fail with InvalidOperationException only in the code path that uses the typo. Instead: use typed clients or a constant for the name.
  • Mistake: Injecting IOptions<T> and expecting a named instance. Why it is wrong: IOptions<T> only returns the default name, so the app quietly uses empty or wrong settings (for example the marketing SMTP host for password resets). Instead: use IOptionsMonitor<T>.Get(name) or IOptionsSnapshot<T>.Get(name).
  • Mistake: Expecting a configuration change to swap a registration at run time. Why it is wrong: the container is fixed after Build(), so the flag flips in App Configuration but the old implementation keeps running until the next restart, which is confusing during an incident. Instead: register both and choose in a resolver or with a feature flag.
  • Mistake: Registering one named client, options instance or keyed service per tenant at start-up. Why it is wrong: adding a tenant needs a redeploy, start-up grows with tenant count and per-key singletons hold memory for every tenant. Instead: one resolver that looks up tenant settings (cached, from configuration or a database) and creates or reuses clients per tenant through IHttpClientFactory.
  • Mistake: Scattering if (env.IsDevelopment()) checks inside services. Why it is wrong: behaviour becomes hard to test, and a production pod with the wrong environment variable silently runs development code paths. Instead: decide once in the composition root.
  • Mistake: Injecting a typed client into a singleton. Why it is wrong: the singleton keeps one handler forever and misses DNS changes, so a partner's failover leaves you calling a dead IP. Instead: consume typed clients from transient or scoped services, or use IHttpClientFactory in singletons.
  • Mistake: Building a dictionary of implementations by hand when keyed services exist. Why it is wrong: it duplicates a built-in feature and skips container validation. Instead: use keyed services for named registrations of arbitrary types, and a factory when the choice needs logic.

🏛 Senior insight: trade-offs

The senior distinction is between deployment-time and run-time variation. Environment and infrastructure choices belong in the composition root and are cheap and obvious there. Anything product-driven (rollouts, tenants, A/B) belongs behind a resolver with a feature flag, because you'll want to change it without a deployment and test both paths. Mixing the two leads to surprise when someone flips a setting and nothing happens.

Option When it fits Cost When not to
if in Program.cs Environment or per-deployment choice Restart to change Feature rollouts
Named options Same class, several configs Name strings Different behaviour, not just settings
Typed/named HttpClient Several remote APIs One registration per API Injected into singletons
Resolver + feature flag Run-time switching Extra indirection and per-call check Choices that never change

Measure with a WebApplicationFactory test per environment that asserts the resolved implementation types, so a wrong branch fails the build.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions named options or reloading configuration Why: Checks the differences between IOptions, IOptionsSnapshot and IOptionsMonitor, including named options
    How to answer

    All three give you the same bound options; they differ in lifetime and freshness.

    • IOptions<T>: singleton, built once on first .Value, never changes, no named options. The default for settings that need a restart anyway.
    • IOptionsSnapshot<T>: scoped, rebuilt once per request (per scope), supports Get(name). A request sees one consistent value. It can't go into singletons, and it rebinds on every request.
    • IOptionsMonitor<T>: singleton, CurrentValue is cached and rebuilt when the configuration change token fires, supports Get(name) and OnChange. Use it in singletons and BackgroundService.

    Changes only arrive if a provider reloads (JSON files, App Configuration refresh), never from environment variables. The trade-off: fresher values mean code that must cope with values changing under it.

  2. When: Candidate mentions HttpClient lifetimes or typed clients in singletons Why: Checks lifetime choice for HttpClient and why typed clients in singletons are a problem
    How to answer

    I choose by state and thread safety, then check dependencies:

    1. Does it hold per-unit-of-work state (a change tracker, the current user)? → scoped.
    2. Is it shared, thread-safe and worth building once (a cache, a client pool, compiled config)? → singleton.
    3. Stateless and cheap? → transient (or singleton if every dependency is a singleton).
    4. A service can't outlive its shortest-lived dependency.

    So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me