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

📚 Interview question

You are writing a NuGet library that other teams will use in their ASP.NET Core apps. How should it integrate with dependency injection? Explain AddMyLibrary() extension methods, options, TryAdd, builder objects, and how you avoid tying consumers to one container.

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.

Senior Theory Advanced aspnet-core dependency-injection library-design nuget options-pattern tryadd

🎯 Key points

  • Expose AddMyLibrary(this IServiceCollection, Action<TOptions>?) in the Microsoft.Extensions.DependencyInjection namespace
  • Reference Microsoft.Extensions.DependencyInjection.Abstractions, not a concrete container
  • Use TryAdd for overridable defaults and TryAddEnumerable for plug-ins, so calling AddX twice is safe
  • Bind configuration through the options pattern with ValidateOnStart; document the OptionsValidationException messages consumers will see
  • Return a builder (IMyLibraryBuilder) for chained configuration, like AddHttpClient and AddHealthChecks
  • Pick and document lifetimes; singletons must be thread-safe and never capture scoped services
  • Treat registrations as public API: changing a lifetime or Add/TryAdd is a breaking change under SemVer
  • Keep the library usable without DI (public constructors, a simple factory)

⏱ 30-second answer

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.

  • Depend on Microsoft.Extensions.DependencyInjection.Abstractions and Options, never on a specific container.
  • Use TryAdd for defaults the app can override and TryAddEnumerable for plug-ins, so calling it twice is harmless.
  • Configure through the options pattern with validation and ValidateOnStart.

The trade-off: an AddX() method is convenient but hides registrations, so lifetimes and overrides must be documented and predictable.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd design it the way AddHttpClient, AddHealthChecks or AddOpenTelemetry work, because that's what consumers expect. There's one entry point, services.AddPaymentsClient(o => ...), in the Microsoft.Extensions.DependencyInjection namespace so it shows up without an extra using. The library references only the abstractions packages, Microsoft.Extensions.DependencyInjection.Abstractions and Microsoft.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 own IPaymentsClock or IRetryPolicy, mine doesn't override it. Plug-in style services use TryAddEnumerable so calling AddPaymentsClient() 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 an IPaymentsBuilder so 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, read IConfiguration sections 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."


Library DI checklist

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

Production example

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

🔍 What the interviewer is checking

Checks the candidate can design a library's DI integration that is predictable, idempotent and container-agnostic.

Green flags

  • Mirrors Microsoft's AddX and builder conventions
  • Uses TryAdd/TryAddEnumerable and explains why
  • Uses options with validation and ValidateOnStart
  • References abstractions only and keeps a non-DI path

Red flags

  • Calls BuildServiceProvider() in the extension method
  • Hard-codes configuration section names inside services
  • Ignores lifetime and override implications

📚 Learn in depth

1. The shape of a good AddX method

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

2. Abstractions packages

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.

3. Overridable defaults

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.

4. Options flow

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.

5. Lifetimes in libraries

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.

6. Usable without DI

Keep public constructors that take options and dependencies explicitly, or a static PaymentsClient.Create(options) helper. This helps console tools, tests and other containers.

Try it yourself

  1. Write AddGreeting() using TryAddSingleton; register your own IGreeter first and confirm yours wins.
  2. Call AddGreeting() twice with a plug-in registered by Add and then by TryAddEnumerable; count instances.
  3. Add ValidateOnStart with a [Required] option, start the host without it and read the error.
  4. Write a test that creates new ServiceCollection().AddGreeting().BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }) and resolves the public services.
  5. Reference only the abstractions package and check the consumer's dependency graph with dotnet list package --include-transitive.

💻 Code

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

⚠ Common mistakes

  • Mistake: Calling 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.
  • Mistake: Using plain 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.
  • Mistake: Registering plug-ins with Add* so AddX() isn't idempotent. Why it is wrong: calling it from two modules duplicates handlers. Instead: TryAddEnumerable.
  • Mistake: Reading 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.
  • Mistake: Depending on a specific container or Scrutor in the public API. Why it is wrong: it forces that container on every consumer. Instead: depend only on the abstractions packages.
  • Mistake: A singleton service depending on something consumers may register as scoped. Why it is wrong: it creates a captive dependency the consumer can't see. Instead: document lifetimes and use IServiceScopeFactory where needed.
  • Mistake: Changing a lifetime or switching 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.
  • Mistake: Hiding what the library registers and failing with vague errors. Why it is wrong: consumers can't debug overrides or missing configuration. Instead: document every registered service type and lifetime in the README, give options validation clear messages ("Payments:ApiKey is required"), and expose the builder's Services so consumers and tests can inspect or adjust registrations.
  • Mistake: Silently registering hosted services or middleware. Why it is wrong: it adds background work and start-up cost the consumer didn't ask for. Instead: make it an explicit builder method.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TryAdd or TryAddEnumerable Why: Checks the exact semantics of registration methods and ordering
    How to 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.

  2. When: Candidate mentions ValidateOnStart or options validation Why: Checks options validation techniques in depth
    How to answer

    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.

  3. When: Candidate says the library should not depend on one container Why: Checks knowledge of conforming containers and what Scrutor or Autofac add
    How to answer

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

    • Scrutor isn't a container; it adds Scan() and Decorate() extension methods to IServiceCollection.
    • Autofac and Lamar replace the provider through 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.

🛠 Real-world problems: how you handle them

Shared payments library double-registers its signing handler
Situation
At [company] a shared internal NuGet package wrapped the [payment provider] API and was used by [n] services. Its AddPayments() method registered handlers with plain Add* calls and read the API key from IConfiguration inside the client's constructor.
Signals
After a refactor, one service started getting HTTP 401 'invalid signature' responses on every payment call; Application Insights dependency telemetry showed 100% failure for the payments dependency starting with the release. Locally, everything worked.
Investigation
Logged the outgoing headers with HTTP logging on HttpClient and saw two signature headers. A test that built the service's real composition root and enumerated IServiceCollection showed SigningHandler registered twice, because two feature modules each called AddPayments(). Reading the library code confirmed Add* rather than TryAdd*/TryAddEnumerable, and no idempotency.
Resolution
Immediate: removed the second AddPayments() call and redeployed, which restored payments within [minutes]. Real fix: released a new library version using TryAdd/TryAddEnumerable, options with ValidateDataAnnotations and ValidateOnStart instead of reading IConfiguration, and a builder for optional webhook handlers.
Prevention
Added library tests that call AddPayments() twice and assert single registration, a consumer test template that builds the host with ValidateOnBuild and ValidateScopes, release notes that call out lifetime changes as breaking, and an alert on payment dependency failure rate.

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.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me