Covers DI design for reusable .NET libraries: IServiceCollection extension methods, options and validation, TryAdd and TryAddEnumerable for overridable defaults, builder objects for chained configuration, depending only on abstractions packages, and lifetime choices.
A library should plug into DI the way Microsoft's own packages do: a single AddMyLibrary(this IServiceCollection services, Action<MyLibraryOptions>? configure = null) extension method that registers everything and returns the collection or a builder for chained configuration.
Microsoft.Extensions.DependencyInjection.Abstractions and Options, never on a specific container.TryAdd for defaults the app can override and TryAddEnumerable for plug-ins, so calling it twice is harmless.ValidateOnStart.The trade-off: an AddX() method is convenient but hides registrations, so lifetimes and overrides must be documented and predictable.
"I'd design it the way
AddHttpClient,AddHealthChecksorAddOpenTelemetrywork, because that's what consumers expect. There's one entry point,services.AddPaymentsClient(o => ...), in theMicrosoft.Extensions.DependencyInjectionnamespace so it shows up without an extra using. The library references only the abstractions packages,Microsoft.Extensions.DependencyInjection.AbstractionsandMicrosoft.Extensions.Options, so it works whether the app uses the built-in provider, Autofac or anything that conforms.Inside, every default goes in with
TryAdd, so if the app has already registered its ownIPaymentsClockorIRetryPolicy, mine doesn't override it. Plug-in style services useTryAddEnumerableso callingAddPaymentsClient()from two modules doesn't double-register handlers. Configuration flows through options:AddOptions<PaymentsOptions>().Configure(configure).ValidateDataAnnotations().ValidateOnStart(), so a missing API key fails at start-up instead of on the first payment. If there's more to configure, I return anIPaymentsBuilderso people can chain.AddWebhookHandler<T>(). For example, at [company] I [built / maintained] [library], and [making AddX idempotent / adding ValidateOnStart] [cut support tickets or start-up failures by N].The mistake I see is libraries that call
BuildServiceProvider()internally, readIConfigurationsections with hard-coded names, register singletons that capture scoped services, or silently add hosted services. A good library makes the composition root more predictable, not less, and it still offers a public constructor so people can use it without a container at all."
| Do | Why |
|---|---|
AddX(this IServiceCollection, Action<TOptions>?) |
Familiar, discoverable entry point |
Put it in namespace Microsoft.Extensions.DependencyInjection |
No extra using needed (the convention Microsoft packages follow) |
Reference *.Abstractions only |
Works with any conforming container |
TryAdd / TryAddEnumerable |
Overridable defaults, idempotent calls |
Options + ValidateOnStart |
Fail fast on bad config |
| Return a builder for extras | Clean chaining, scoped to your library |
| Document lifetimes | Consumers can reason about captive dependencies |
| Don't | Why |
|---|---|
services.BuildServiceProvider() inside AddX |
Second container, duplicate singletons |
Read IConfiguration["MyLib:Key"] inside services |
Hidden coupling to section names |
| Register hosted services without saying so | Surprise background work and start-up cost |
| Depend on Autofac or Scrutor in the public API | Forces your container on consumers |
An internal payments client originally registered its HTTP handler with AddSingleton and read its API key from IConfiguration in the constructor. Two teams called AddPayments() from different modules and every request was signed twice, causing 401s. Rewriting it with TryAddEnumerable, options validation and a builder fixed the double registration, and ValidateOnStart turned 'payments fail at 2 am' into 'deployment fails health checks'.
Checks the candidate can design a library's DI integration that is predictable, idempotent and container-agnostic.
Green flags
AddX and builder conventionsTryAdd/TryAddEnumerable and explains whyValidateOnStartRed flags
BuildServiceProvider() in the extension methodservices.AddPaymentsClient(o => o.BaseAddress = ...) ← public entry point
├─ AddOptions<PaymentsOptions>()...ValidateOnStart()
├─ TryAddSingleton<IPaymentsClock, SystemPaymentsClock>()
├─ AddHttpClient<IPaymentsClient, PaymentsClient>()
│ .AddHttpMessageHandler<SigningHandler>()
├─ TryAddTransient<SigningHandler>()
└─ return new PaymentsBuilder(services) ← for chained extras
Microsoft.Extensions.DependencyInjection.Abstractions contains IServiceCollection, ServiceDescriptor, the Add*/TryAdd* extensions, IServiceProvider helpers and ActivatorUtilities. It has no provider implementation, so it doesn't drag a container into consumers. The same split exists for logging and options.
The consumer controls order. With TryAdd, an app that registers its own implementation before calling AddX wins. If you need to support overriding after, document services.Replace(...) or offer a builder method like .UseClock<TClock>() that calls Replace internally.
AddPaymentsClient(configure)
→ OptionsBuilder<PaymentsOptions>
.Configure(configure) (code)
.BindConfiguration("Payments") (optional; let the app choose the section)
.ValidateDataAnnotations()
.ValidateOnStart() (runs when the host starts)
Provide overloads: one taking Action<TOptions>, one taking IConfiguration section, so apps choose.
Prefer singletons for stateless, thread-safe clients (they're cheap and safe if they don't capture scoped services). Use AddHttpClient for HTTP so handler lifetimes and DNS changes are managed by IHttpClientFactory. Never make a singleton depend on something the consumer might register as scoped; if you must, take IServiceScopeFactory and create scopes.
Keep public constructors that take options and dependencies explicitly, or a static PaymentsClient.Create(options) helper. This helps console tools, tests and other containers.
AddGreeting() using TryAddSingleton; register your own IGreeter first and confirm yours wins.AddGreeting() twice with a plug-in registered by Add and then by TryAddEnumerable; count instances.ValidateOnStart with a [Required] option, start the host without it and read the error.new ServiceCollection().AddGreeting().BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }) and resolves the public services.dotnet list package --include-transitive.A library entry point with options, overridable defaults and a builder.
// Library project: references Microsoft.Extensions.DependencyInjection.Abstractions,
// Microsoft.Extensions.Options.DataAnnotations and Microsoft.Extensions.Http.
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Payments.Client;
namespace Microsoft.Extensions.DependencyInjection; // discoverable without an extra using
public static class PaymentsServiceCollectionExtensions
{
public static IPaymentsBuilder AddPaymentsClient(
this IServiceCollection services, Action<PaymentsOptions>? configure = null)
{
services.AddOptions<PaymentsOptions>()
.Configure(o => configure?.Invoke(o))
.ValidateDataAnnotations()
.ValidateOnStart(); // fail at start-up, not on the first payment
services.TryAddSingleton(TimeProvider.System); // app can register its own first
services.TryAddTransient<SigningHandler>();
// IHttpClientFactory manages handler lifetime and DNS refresh.
services.AddHttpClient<IPaymentsClient, PaymentsClient>()
.AddHttpMessageHandler<SigningHandler>();
return new PaymentsBuilder(services);
}
}
namespace Payments.Client;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public sealed class PaymentsOptions
{
[Required, Url] public string BaseAddress { get; set; } = "";
[Required] public string ApiKey { get; set; } = "";
}
public interface IPaymentsBuilder
{
IServiceCollection Services { get; }
IPaymentsBuilder AddWebhookHandler<THandler>() where THandler : class, IWebhookHandler;
}
internal sealed class PaymentsBuilder(IServiceCollection services) : IPaymentsBuilder
{
public IServiceCollection Services => services;
public IPaymentsBuilder AddWebhookHandler<THandler>() where THandler : class, IWebhookHandler
{
// Idempotent: registering the same handler twice adds it once.
services.TryAddEnumerable(ServiceDescriptor.Scoped<IWebhookHandler, THandler>());
return this;
}
}
public interface IWebhookHandler { Task HandleAsync(string payload, CancellationToken ct); }
public interface IPaymentsClient { Task<string> ChargeAsync(decimal amount, CancellationToken ct); }
internal sealed class PaymentsClient(HttpClient http) : IPaymentsClient
{
public Task<string> ChargeAsync(decimal amount, CancellationToken ct) => Task.FromResult("ok");
}
internal sealed class SigningHandler : DelegatingHandler;
// Consumer's Program.cs
builder.Services.AddPaymentsClient(o => builder.Configuration.GetSection("Payments").Bind(o))
.AddWebhookHandler<RefundWebhookHandler>();
services.BuildServiceProvider() inside AddX to read options or resolve a dependency. Why it is wrong: it creates a second container with its own singletons and missing later registrations. Instead: use options, IConfigureOptions<T> or factory delegates.Add* for defaults. Why it is wrong: the library silently overrides the app's own registrations. Instead: TryAdd for defaults, and document how to override.Add* so AddX() isn't idempotent. Why it is wrong: calling it from two modules duplicates handlers. Instead: TryAddEnumerable.IConfiguration["MyLibrary:Key"] inside services. Why it is wrong: the library dictates section names and can't be configured in code or validated. Instead: options with an Action<TOptions> overload and an IConfiguration overload.IServiceScopeFactory where needed.TryAdd to Add in a minor release. Why it is wrong: consumers' overrides and thread-safety assumptions break without a compile error. Instead: treat DI registrations as public API, follow SemVer and call these changes out in release notes.Services so consumers and tests can inspect or adjust registrations.A library's DI surface is a public API with compatibility rules like any other. Changing a lifetime from transient to singleton, or a TryAdd to an Add, is a breaking change for someone. So I version it deliberately, write tests that build a container with ValidateOnBuild and ValidateScopes on, and test the override paths (app registers first, app replaces after).
I also keep the library usable without DI. Not everyone uses the Generic Host, and a public constructor or factory method makes unit testing and console tools simple.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
AddX() returning IServiceCollection |
Simple libraries with a few services | Minimal | When there are many optional extras |
AddX() returning a builder |
Libraries with plug-ins and options | A builder type to maintain | Tiny libraries |
| No DI integration, just constructors | Pure utilities, value types | Consumers wire it themselves | Libraries needing options, HTTP or logging |
| Container-specific modules (Autofac) | Internal libraries in an Autofac-only estate | Locks consumers in | Public NuGet packages |
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.
Options validation runs as the last step when an options object is built. ValidateDataAnnotations() applies attributes such as [Required], [Range] and [Url]; Validate(o => ..., "message") adds small rules; IValidateOptions<T> handles cross-property rules, named options or rules that need services.
Without ValidateOnStart() validation is lazy: a missing key surfaces as a 500 on the first request that reads the options, possibly hours after the deployment looked healthy. With it, the host validates during start-up, the process exits with every failure listed, and the orchestrator keeps the old version serving.
Nested objects need [ValidateObjectMembers] and collections [ValidateEnumeratedItems]. For Native AOT, the [OptionsValidator] source generator writes the DataAnnotations checks at compile time with no reflection.
The trade-off: a few attributes and a class, in exchange for configuration errors becoming start-up errors with clear messages.
The built-in container is deliberately a minimum: constructor injection, singleton/scoped/transient, open generics, IEnumerable<T> and, since .NET 8, keyed services. It leaves out property injection, assembly scanning, decorators, interception, child or tagged scopes and implicit Func<T>/Lazy<T>.
Scan() and Decorate() extension methods to IServiceCollection.UseServiceProviderFactory and add modules, decorators, interception and richer scopes.My default is built-in plus Scrutor if needed. The trade-off: a full container adds power but also a dependency, start-up cost and a learning curve for every new developer.
How to tell it (STAR)
**S:** At [company] a shared payments library was used by [n] services, and after a refactor one of them failed every payment with 401s. **T:** I needed to restore payments fast and stop it happening in other consumers. **A:** I turned on outgoing HTTP logging and saw two signature headers, then wrote a test that enumerated the service collection and found the signing handler registered twice, because two modules each called AddPayments() and the library used plain Add calls. I removed the duplicate call to restore service, then rewrote the library's registration with TryAdd and TryAddEnumerable, moved configuration to validated options with ValidateOnStart and published it with a test proving AddPayments() is idempotent. **R:** Payments recovered in [minutes], and across the [n] consuming services we've had [zero] registration-related incidents since; two misconfigured deployments were caught by start-up validation instead of in production.
Last updated 23 Nov 2026.