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.
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.
"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, andIHttpClientFactory.CreateClient(\"auspost\")gives you a client built from it with pooled handlers. I usually prefer a typed client,AddHttpClient<AusPostClient>(), because the consumer just injectsAusPostClient. For settings, named options let the same class carry two configurations:Configure<SmtpOptions>(\"transactional\", ...)andConfigure<SmtpOptions>(\"marketing\", ...), read withIOptionsMonitor<SmtpOptions>.Get(name). PlainIOptions<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.Environmentandbuilder.Configurationare available beforeBuild(), so I can register aFakeEmailSenderin Development, or pickAzureBlobStoreversusLocalFileStorefrom aStorage:Providersetting. 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
IOptionsMonitoror a feature flag per call. The other mistake is a typo in a named client:CreateClientwith an unknown name quietly returns an unconfigured client, and you find out when requests go to a relative URL and fail."
| 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")] |
| 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 |
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.
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
IOptions<T> gives only the default nameRed flags
IsDevelopment() inside business classesnew HttpClient() per partnerAddHttpClient("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.
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.
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.
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.
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.
CreateClient with a misspelt name and inspect BaseAddress.SmtpOptions and print IOptions<SmtpOptions>.Value versus IOptionsMonitor<SmtpOptions>.Get("marketing").WebApplicationFactory test that asserts which implementation resolves in each environment.appsettings.json with reloadOnChange to see it switch without a restart.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;
}
}
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.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).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.IHttpClientFactory.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.IHttpClientFactory in singletons.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.
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.
I choose by state and thread safety, then check dependencies:
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.
Last updated 23 Nov 2026.