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

📚 Interview question

Sometimes a service needs an object it can't get from the container at construction time: a dependency that is expensive and rarely used, a new instance per operation, or one that needs a run-time value such as a tenant or file name. Show how you would solve this with factory delegates, Func<T>, Lazy<T> and ActivatorUtilities, and explain the trade-offs.

Shows factory injection in Microsoft.Extensions.DependencyInjection: factory registrations, explicit Func<T> and Lazy<T> registrations, typed factory interfaces, ActivatorUtilities.CreateFactory for run-time arguments, and disposal and lifetime pitfalls.

Mid-Level Coding Intermediate activatorutilities csharp dependency-injection factory-injection lazy-initialisation

🎯 Key points

  • Factory registration: AddScoped<T>(sp => ...) runs logic at resolution time
  • Built-in container does not auto-supply Func<T> or Lazy<T>; register them explicitly
  • Prefer a typed factory interface (IReportExporterFactory) over raw Func<string, T>
  • ActivatorUtilities.CreateFactory gives a cached ObjectFactory that mixes container and run-time arguments
  • Objects created by a factory or ActivatorUtilities are owned and disposed by the caller
  • A factory resolving from the root provider can create captive dependencies
  • Lazy<T> defers cost but hides a dependency; a smell when used to break cycles
  • Test the factory, not the container

⏱ 30-second answer

When the container can't build something up front, inject a factory instead of the object.

  • A factory registration (AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.
  • Unlike Autofac, the built-in container (still true in .NET 10) does not auto-supply Func<T> or Lazy<T>; you register them explicitly.
  • For run-time values, define a small typed factory interface and implement it with ActivatorUtilities.CreateFactory (the generic ObjectFactory<T> overload arrived in .NET 8), which mixes your argument with container services and caches the reflection.

The key rule: anything a factory creates is owned by the caller, who must dispose it. The trade-off is flexibility against hidden lifetimes: factories are the main way captive and leaked dependencies sneak in.

🗣 Full answer (senior)

How I would answer this in an interview

"The container is great at building graphs where everything is known at start-up. Three cases break that: a dependency that's expensive and only used on one code path, a dependency you need a fresh instance of per operation, and an object that needs a run-time value like a file name or tenant id. In all three I inject a factory rather than the thing itself.

For the expensive one, Lazy<T> works, but the built-in container won't give you Lazy<T> or Func<T> automatically, unlike Autofac. I register them explicitly, for example services.AddTransient(sp => new Lazy<IPdfRenderer>(sp.GetRequiredService<IPdfRenderer>)). For run-time arguments I prefer a typed factory: an IReportExporterFactory with Create(string reportName). Its implementation uses ActivatorUtilities.CreateFactory once, which returns an ObjectFactory delegate; at call time I pass the report name and it pulls ILogger and the rest from the container. That's much clearer than a raw Func<string, IReportExporter> floating around, and it's easy to fake in tests.

The mistake I see is ownership. If my factory creates an IDisposable, the container doesn't track it, so the caller must using it. And if the factory is a singleton holding the root IServiceProvider, anything scoped it resolves becomes effectively a singleton: that's a captive dependency in disguise. So a factory either receives the current scope's provider or creates its own scope, and it's honest about who disposes what."


Which tool for which problem

Problem Tool Notes
Construction needs logic or config Factory registration sp => ... Container owns and disposes the result
Expensive, rarely used dependency Lazy<T> (registered explicitly) Hides the dependency a little; measure first
New instance per operation Func<T> or a typed factory Caller owns disposal
Needs a run-time value Typed factory + ActivatorUtilities.CreateFactory Clear API, testable, no per-call reflection
Choose between implementations by key Keyed services or IEnumerable<T> Covered by the Strategy and keyed-services questions

Ownership rules

Created by Disposed by
Container (any registration, including factory registrations) Container, at scope or root disposal
Your factory calling new or ActivatorUtilities The caller
Func<T> that calls sp.GetRequiredService<T>() Container (the scope sp belongs to)

Production example

An export service needed a CsvExporter per report with the report name in its constructor. The first version used ActivatorUtilities.CreateInstance on every request, which showed up at about 4% of CPU in a dotnet-trace profile at 300 requests per second. Moving to a typed factory that caches ActivatorUtilities.CreateFactory dropped it below the noise, and the exporter's FileStream was finally disposed because the caller used await using.

🔍 What the interviewer is checking

Checks the candidate can handle run-time arguments and deferred creation with the built-in container without creating captive dependencies or leaks.

Green flags

  • Knows Func<T>/Lazy<T> aren't automatic in the built-in container
  • Uses a typed factory and caches ObjectFactory
  • States clearly who disposes factory-created objects
  • Spots the root-provider captive dependency risk

Red flags

  • Injects IServiceProvider everywhere and calls GetService with strings of logic
  • Ignores disposal of created objects
  • Uses Lazy<T> to paper over circular dependencies

📚 Learn in depth

1. Why the container can't do it alone

The container builds objects from types it knows at registration time. Run-time values (the current file, a user's choice) don't exist then.

Start-up:   IServiceCollection knows types and lifetimes
Request:    the report name arrives in the URL
            → something must combine the two: a factory

2. Factory registrations

services.AddScoped<IStorage>(sp =>
    sp.GetRequiredService<IOptions<StorageOptions>>().Value.UseBlob
        ? ActivatorUtilities.CreateInstance<BlobStorage>(sp)
        : ActivatorUtilities.CreateInstance<FileStorage>(sp));

The delegate runs on each resolution according to the lifetime. Because the container invoked it, the returned object is tracked and disposed with the scope. ValidateOnBuild can't look inside the delegate.

3. Func

Autofac has "implicit relationship types": ask for Func<T> or Lazy<T> and it supplies them. The built-in container does not. You register them:

services.AddTransient<Func<IPdfRenderer>>(sp => sp.GetRequiredService<IPdfRenderer>);
services.AddTransient(sp => new Lazy<IPdfRenderer>(sp.GetRequiredService<IPdfRenderer>));

The captured sp is the provider of the scope that resolved the Func/Lazy, so instances live in that scope. If the Func is captured by a singleton, sp is the root provider and scoped services become captive.

4. ActivatorUtilities.CreateFactory

CreateFactory(typeof(CsvExporter), [typeof(string)])  ── once, reflection
        │
        ▼
ObjectFactory(sp, ["monthly"])  ── per call, fast: "monthly" → string param,
                                    ILogger<CsvExporter> → from sp

.NET 8 added a generic ObjectFactory<T> overload so you avoid the cast.

5. Typed factories vs raw delegates

A Func<string, IExporter> doesn't say what the string means and can't be found with "Go to implementation". An IExporterFactory.Create(string reportName) is self-documenting, mockable and a single place to enforce disposal rules.

Try it yourself

  1. BenchmarkDotNet: compare ActivatorUtilities.CreateInstance per call with a cached ObjectFactory over 100,000 creations.
  2. Register a Func<IScopedThing>, capture it in a singleton, and check with ValidateScopes whether anything warns you (it won't). Log instance ids across two requests.
  3. Create a disposable exporter through a factory, forget to dispose it, and watch handles grow with dotnet-counters.
  4. Replace a Func<string, IExporter> with a typed factory and write a unit test with a fake factory.

💻 Code

A typed factory using a cached ObjectFactory, plus explicit Lazy

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IReportExporterFactory, ReportExporterFactory>();
builder.Services.AddScoped<IPdfRenderer, PdfRenderer>();
// The built-in container does not supply Lazy<T> automatically.
builder.Services.AddScoped(sp => new Lazy<IPdfRenderer>(sp.GetRequiredService<IPdfRenderer>));

var app = builder.Build();

app.MapGet("/reports/{name}", async (string name, IReportExporterFactory factory, HttpContext http, CancellationToken ct) =>
{
    // The caller owns what the factory creates.
    await using var exporter = factory.Create(name, http.RequestServices);
    return Results.Text(await exporter.ExportAsync(ct), "text/csv");
});

app.Run();

public interface IReportExporterFactory
{
    ReportExporter Create(string reportName, IServiceProvider scopedProvider);
}

public sealed class ReportExporterFactory : IReportExporterFactory
{
    // Reflection happens once; each Create is a fast delegate call.
    private static readonly ObjectFactory<ReportExporter> Factory =
        ActivatorUtilities.CreateFactory<ReportExporter>([typeof(string)]);

    // Takes the request's provider so scoped dependencies are not captured by this singleton.
    public ReportExporter Create(string reportName, IServiceProvider scopedProvider) =>
        Factory(scopedProvider, [reportName]);
}

public sealed class ReportExporter(string reportName, ILogger<ReportExporter> logger) : IAsyncDisposable
{
    public Task<string> ExportAsync(CancellationToken ct)
    {
        logger.LogInformation("Exporting {Report}", reportName);
        return Task.FromResult("id,total\n1,99.95");
    }

    public ValueTask DisposeAsync() => ValueTask.CompletedTask; // would close streams
}

public interface IPdfRenderer;
public sealed class PdfRenderer : IPdfRenderer;

⚠ Common mistakes

  • Mistake: Expecting Func<T> or Lazy<T> to resolve automatically. Why it is wrong: that is an Autofac feature; the built-in container (through .NET 10) throws "Unable to resolve service". Instead: register them explicitly or use a typed factory.
  • Mistake: A singleton factory resolving scoped services from the root provider. Why it is wrong: the scoped service lives for the app's lifetime (a captive dependency) and may be shared across threads. Instead: pass the current scope's provider or create a scope with IServiceScopeFactory.
  • Mistake: Not disposing objects a factory creates. Why it is wrong: the container doesn't track them, so handles and connections leak. Instead: document ownership and use using/await using at the call site.
  • Mistake: Calling ActivatorUtilities.CreateInstance on a hot path. Why it is wrong: it reflects every call. Instead: cache an ObjectFactory from CreateFactory.
  • Mistake: Passing raw Func<string, T> around. Why it is wrong: the parameter's meaning is unclear and it's hard to navigate and fake. Instead: define a typed factory interface.
  • Mistake: Using Lazy<T> to break a circular dependency. Why it is wrong: it hides a design problem and can still deadlock or recurse at run time. Instead: redesign the responsibilities.
  • Mistake: Exposing Lazy<T> in public constructors. Why it is wrong: it leaks an implementation detail (that the dependency is expensive to build) into every consumer's signature and tests, breaking encapsulation. Instead: keep laziness inside the implementation, for example a decorator or the service itself creating the expensive part on first use.
  • Mistake: Adding Lazy<T> everywhere "for performance". Why it is wrong: most services are cheap to construct; laziness adds indirection and thread-safety cost. Instead: measure construction cost first.

🏛 Senior insight: trade-offs

Factories are where container guarantees end. ValidateOnBuild can't see inside them, ValidateScopes doesn't know what a singleton factory resolves later, and disposal becomes the caller's job. So I keep factories small, typed and explicit about the provider they use, and I put a test around anything that creates disposables.

In production I watch for the symptoms of factory misuse rather than hoping reviews catch it: process handle count and working set in dotnet-counters or Application Insights (leaked disposables), ObjectDisposedException or DbContext concurrency exceptions (scoped objects captured by a singleton factory), and CPU samples in ActivatorUtilities (missing CreateFactory caching). A load test that asserts handle count stays flat catches most of these before release.

Option When it fits Cost When not to
Factory registration (sp => ...) Choosing or configuring an implementation at resolution Not validated at build When a plain type registration works
Lazy<T> Measured expensive construction on a rare path Indirection, hidden dependency To break cycles
Typed factory + ObjectFactory Run-time arguments, many creations One small class; one-off reflection One-off creation in start-up code
Keyed services Selecting a known implementation by key Keys are stringly typed Run-time data that isn't a fixed key

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the Factory pattern Why: Checks when DI makes a hand-written factory unnecessary
    How to answer
    • A simple factory is one method, usually a switch, that returns the right implementation. It isn't a GoF pattern, but it's fine for a small closed set.
    • Factory Method lets a base class define the creation step while subclasses choose the type. In .NET, DbConnection.CreateCommand() calls the protected abstract CreateDbCommand(), so SqlConnection returns a SqlCommand.
    • Abstract Factory is an interface that creates a family of related objects that must match. DbProviderFactory creates the connection, command and parameter for one provider, and DbDataSource (.NET 7+) is the modern equivalent.

    In an ASP.NET Core app the DI container is the factory: registrations, factory delegates and keyed services cover most cases. A hand-written factory still pays off when creation needs run-time data the container doesn't have. The trap is that one taking IServiceProvider everywhere becomes a service locator.

  2. When: Candidate needs to choose an implementation at run time Why: Checks keyed services and IEnumerable-based selection versus factories
    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 mentions ActivatorUtilities Why: Checks deeper knowledge of how ActivatorUtilities chooses constructors
    How to answer

    When you resolve a service, Microsoft.Extensions.DependencyInjection builds a call site: a tree describing how to create it (which constructor, which dependencies, which lifetime cache). It picks the constructor with the most parameters it can satisfy, and throws an InvalidOperationException if two equally long constructors are both satisfiable.

    Call sites are cached per service type. Early resolutions are interpreted; once a service has been resolved repeatedly it is compiled in the background to an expression-tree or IL delegate, so later resolutions are a delegate call plus lifetime lookups.

    GetService returns null for an unregistered type and GetRequiredService throws. ActivatorUtilities.CreateInstance builds a type that isn't registered, filling some constructor parameters from the container and others from arguments you pass.

    The trade-off: the built-in container is fast and predictable but deliberately minimal.

🛠 Real-world problems: how you handle them

Export endpoint leaks file handles through a factory
Situation
A reporting API in [company] generated CSV and PDF exports for [number] customers. Each export used an exporter built by a hand-written factory with the report name as a constructor argument. Traffic was about [300] export requests per second at month end.
Signals
dotnet-counters showed handle count and working set climbing steadily during the month-end run; the App Service instance restarted after [n] hours with 'Too many open files' errors in the logs. A dotnet-trace CPU profile showed ActivatorUtilities.CreateInstance at roughly 4% of CPU.
Investigation
Took a dump with dotnet-dump and ran `dumpheap -stat`, which showed thousands of live FileStream and exporter instances. `gcroot` showed them rooted only by finalisation, meaning nobody disposed them. Reading the factory confirmed it used ActivatorUtilities.CreateInstance per call and returned the exporter without any disposal contract; callers assumed the container would dispose it.
Resolution
Immediate: added `await using` around the exporter in the endpoint and redeployed. Real fix: introduced a typed IReportExporterFactory that caches ActivatorUtilities.CreateFactory, takes the request scope's provider, and documents that the caller owns the result; made the exporter IAsyncDisposable.
Prevention
Added a code review checklist item for factories (who disposes, which provider), enabled the CA2000 analyser for undisposed objects, added a load test that checks handle count stays flat, and an alert on process handle count in Application Insights.

How to tell it (STAR)

**S:** Our reporting API at [company] kept restarting during month-end exports with 'too many open files'. **T:** I had to find the leak quickly because [number] customers were waiting on their reports. **A:** I watched handle count climb in dotnet-counters, took a dump, and found thousands of undisposed FileStreams held by exporters our factory created with ActivatorUtilities. The container never tracked them, and the callers assumed it did. I added await using immediately, then replaced the factory with a typed one that caches CreateFactory and makes ownership explicit. **R:** Handle count stayed flat through the next month end, restarts went from [n] a day to zero, and the factory's CPU cost dropped from about 4% to unmeasurable.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me