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

๐Ÿ“š Interview question

Write a factory for objects that need both injected services and run-time arguments, for example a report exporter created per request with a format and a tenant id. Show a registered Func<string, T>, a typed factory interface, and ActivatorUtilities.CreateFactory, and explain who owns and disposes the objects the factory creates.

Building factories for objects that mix DI dependencies and run-time arguments: Func<string, T> registrations, typed factory interfaces, ActivatorUtilities.CreateInstance versus a cached ObjectFactory from CreateFactory, and the disposal and lifetime rules for objects the container does not track.

Intermediate Coding Intermediate activatorutilities csharp dependency-injection factory-pattern idisposable

๐ŸŽฏ Key points

  • Run-time values (format, tenant id) can't come from the container, so a factory combines them with injected services
  • A typed factory interface (IReportExporterFactory.Create(format, tenantId)) is discoverable and mockable; a Func<string, T> is opaque and best kept internal
  • Group several run-time arguments in a record (ExportRequest) so ActivatorUtilities' by-type matching isn't ambiguous
  • ActivatorUtilities.CreateInstance<T>(sp, args) fills the remaining constructor parameters from DI
  • ActivatorUtilities.CreateFactory returns an ObjectFactory you cache once, avoiding per-call constructor lookup
  • Objects created with ActivatorUtilities are not tracked by the container: the caller owns disposal, within the creating scope
  • Match the factory's lifetime to its dependencies: a singleton factory must not build objects with scoped dependencies from the root

โฑ 30-second answer

When an object needs injected services plus values only known at run time, the container can't build it alone, so you write a factory. Three shapes: a registered Func<string, IReportExporter> (light, but opaque, so keep it internal), a typed factory interface such as IReportExporterFactory.Create(format, tenantId) (discoverable and easy to fake), and inside the factory, ActivatorUtilities, which takes your run-time arguments and fills the other constructor parameters from DI. It matches arguments by type, so group several into a record. ActivatorUtilities.CreateFactory gives a cached ObjectFactory, so the constructor lookup happens once. The key trade-off is ownership: objects created this way aren't tracked by the container, so the caller must dispose them, and the factory must resolve scoped services from the current scope, not the root.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"The container can build anything whose constructor parameters are all registered services. A report exporter that needs a format and a tenant id from the request breaks that rule, so I put a factory in between. My default is a small typed factory interface, IReportExporterFactory with Create(ReportFormat format, Guid tenantId). Consumers see exactly what they can ask for, and in unit tests I fake it in one line. A registered Func<string, IReportExporter> is fine for something tiny, but nobody can tell from the signature what strings are allowed.

Inside the factory I use ActivatorUtilities. CreateInstance<CsvExporter>(provider, tenantId) matches my run-time arguments to constructor parameters by type and resolves the rest, like ILogger<CsvExporter> and the DbContext, from the provider. If it's called a lot, I call ActivatorUtilities.CreateFactory once to get an ObjectFactory delegate and cache it, so the constructor isn't looked up with reflection every time.

The mistake I see is forgetting ownership. The container only disposes what it created. An exporter built with ActivatorUtilities holding a file stream is the caller's to dispose, so I return it as IDisposable or IAsyncDisposable and callers use await using. The other mistake is a singleton factory that receives the root IServiceProvider and builds objects with scoped dependencies from it: those DbContexts live forever. I register the factory as scoped, so it gets the request's provider. A factory is the honest answer to run-time arguments, as long as it's clear who owns what it returns."


Shapes of factory

Shape Registration Good for Weakness
Func<string, IReportExporter> AddScoped<Func<string, IReportExporter>>(sp => fmt => ...) One-off, internal Opaque signature; hard to discover
Typed factory interface AddScoped<IReportExporterFactory, ReportExporterFactory>() Public use, tests One more type
ActivatorUtilities.CreateInstance Used inside a factory Mixed run-time + DI args Reflection per call
Cached ObjectFactory CreateFactory(type, argTypes) once Hot paths Slightly more code
Keyed services AddKeyed* Variant chosen by a fixed key, no extra args Can't pass run-time arguments

Ownership

Created by Tracked for disposal? Who disposes
Container (GetRequiredService) Yes, by the scope The scope
ActivatorUtilities / ObjectFactory No The caller
new in a factory No The caller

Production example

In a [multi-tenant reporting] API the exporter factory was originally a singleton using the root provider. Every export created a DbContext that was never disposed, and memory grew by about 300 MB a day. Making the factory scoped and returning IAsyncDisposable exporters used with await using flattened memory, and caching the ObjectFactory cut factory overhead from about 4 ยตs to under 1 ยตs per call.

๐Ÿ” What the interviewer is checking

Checks whether the candidate can combine DI with run-time arguments correctly and understands that factory-created objects fall outside the container's lifetime management.

Green flags

  • Prefers a typed factory interface and explains why
  • Uses ActivatorUtilities and knows about cached ObjectFactory
  • States that the caller owns disposal of factory-created objects
  • Matches the factory's lifetime to the dependencies it resolves

Red flags

  • Registers run-time values as services
  • Injects IServiceProvider everywhere instead of a factory
  • Assumes the container disposes everything

๐Ÿ“š Learn in depth

1. Why the container can't do it

Microsoft.Extensions.DependencyInjection builds call sites from registered types only. A Guid tenantId parameter has no registration, so the container would fail (or worse, if you registered Guid as a service). Run-time data belongs in method arguments or factories, not in registrations.

2. ActivatorUtilities

ActivatorUtilities.CreateInstance<CsvExporter>(sp, tenantId)
   -> find public constructors
   -> pick the one that best matches the given args by type (or [ActivatorUtilitiesConstructor])
   -> for each parameter: given arg of matching type? use it : sp.GetService(type)
   -> missing and no default value? throw InvalidOperationException

It's the same mechanism ASP.NET Core uses for conventional middleware and for controllers (with ServiceBasedControllerActivator aside). Arguments are matched by type, so two string arguments are ambiguous; wrap them in a record such as ExportRequest.

3. ObjectFactory

ActivatorUtilities.CreateFactory(typeof(CsvExporter), [typeof(Guid)]) analyses the constructor once and returns an ObjectFactory delegate (IServiceProvider sp, object?[]? args) => object. A generic CreateFactory<T> overload exists in newer versions. Cache it in a static field or in a singleton holder; calling it then costs one delegate call plus the service resolutions.

4. Ownership and disposal

The container's scope keeps a list of disposables it created. ActivatorUtilities creates the object directly, so the scope never hears of it. Dependencies it resolved are tracked (they came from sp.GetService), so they are disposed with the scope, possibly before your object if you keep it longer. Rule: a factory-created object should not outlive the scope whose provider built it.

request scope
  |- DbContext (tracked, disposed at end of request)
  '- CsvExporter (NOT tracked) -> holds DbContext
        if kept past the request -> ObjectDisposedException

5. Which provider?

A factory registered as a singleton receives the root provider. Anything scoped it resolves from there becomes a root-scoped object that is never released (and ValidateScopes throws in Development). Register factories that create scoped-dependent objects as scoped, or have them take an IServiceProvider argument from the caller's scope.

Try it yourself

  1. Build an exporter with ActivatorUtilities.CreateInstance and add a logged Dispose; end the scope and confirm the exporter isn't disposed.
  2. Register the factory as a singleton with ValidateScopes = true and see the exception when it resolves a scoped DbContext.
  3. Benchmark CreateInstance against a cached ObjectFactory with BenchmarkDotNet.
  4. Give a constructor two string parameters and observe the ambiguity; fix it with a record argument.
  5. Write a unit test for a consumer by faking IReportExporterFactory without any container.

๐Ÿ’ป Code

A typed factory using a cached ObjectFactory, a registered Func alternative, and correct ownership (.NET 10):

using Microsoft.Extensions.DependencyInjection;

namespace Reporting;

public enum ReportFormat { Csv, Pdf }

public interface IReportExporter : IAsyncDisposable
{
    Task ExportAsync(Stream output, CancellationToken ct);
}

public sealed class CsvExporter(Guid tenantId, ReportingDbContext db, ILogger<CsvExporter> log) : IReportExporter
{
    public async Task ExportAsync(Stream output, CancellationToken ct)
    {
        log.LogInformation("Exporting CSV for tenant {TenantId}", tenantId);
        await using var writer = new StreamWriter(output, leaveOpen: true);
        await foreach (var row in db.Sales.Where(s => s.TenantId == tenantId).AsAsyncEnumerable().WithCancellation(ct))
            await writer.WriteLineAsync($"{row.Id},{row.Total}");
    }

    public ValueTask DisposeAsync() => ValueTask.CompletedTask; // owns no resources itself
}

public interface IReportExporterFactory
{
    IReportExporter Create(ReportFormat format, Guid tenantId);
}

// Scoped: receives the request's provider, so the DbContext it injects is the request's one.
public sealed class ReportExporterFactory(IServiceProvider provider) : IReportExporterFactory
{
    // Constructor analysis happens once per process, not per call.
    private static readonly ObjectFactory CsvFactory =
        ActivatorUtilities.CreateFactory(typeof(CsvExporter), [typeof(Guid)]);
    private static readonly ObjectFactory PdfFactory =
        ActivatorUtilities.CreateFactory(typeof(PdfExporter), [typeof(Guid)]);

    public IReportExporter Create(ReportFormat format, Guid tenantId) => format switch
    {
        ReportFormat.Csv => (IReportExporter)CsvFactory(provider, [tenantId]),
        ReportFormat.Pdf => (IReportExporter)PdfFactory(provider, [tenantId]),
        _ => throw new ArgumentOutOfRangeException(nameof(format), format, "Unsupported format.")
    };
}

Registration, a Func alternative, and a caller that owns disposal:

builder.Services.AddScoped<IReportExporterFactory, ReportExporterFactory>();

// Lighter alternative: opaque to callers, fine for internal one-offs.
builder.Services.AddScoped<Func<Guid, IReportExporter>>(sp =>
    tenantId => ActivatorUtilities.CreateInstance<CsvExporter>(sp, tenantId));

app.MapGet("/reports/{tenantId:guid}", async (
    Guid tenantId, ReportFormat format, IReportExporterFactory factory,
    HttpResponse response, CancellationToken ct) =>
{
    // The container doesn't track this object, so the caller disposes it.
    await using var exporter = factory.Create(format, tenantId);
    response.ContentType = format == ReportFormat.Csv ? "text/csv" : "application/pdf";
    await exporter.ExportAsync(response.Body, ct);
});

โš  Common mistakes

  • Mistake: Registering run-time values (a tenant id, a file name) as services so the container can inject them. Why it is wrong: registrations are fixed at start-up and shared. Instead: pass run-time values through a factory method.
  • Mistake: Assuming the container disposes objects built with ActivatorUtilities. Why it is wrong: only container-created objects are tracked. Instead: return IDisposable/IAsyncDisposable and have the caller use using/await using.
  • Mistake: Registering the factory as a singleton when it builds objects with scoped dependencies. Why it is wrong: it resolves them from the root provider, so they are never released (or ValidateScopes throws). Instead: register the factory as scoped.
  • Mistake: Calling ActivatorUtilities.CreateInstance on a hot path. Why it is wrong: it analyses constructors with reflection every call. Instead: cache an ObjectFactory from CreateFactory.
  • Mistake: Passing two arguments of the same type (string format, string region). Why it is wrong: ActivatorUtilities matches by type, so it is ambiguous. Instead: wrap them in a record.
  • Mistake: Keeping a factory-created object past the scope that built it. Why it is wrong: its injected scoped dependencies are disposed with the scope. Instead: use the object within the scope, or create a scope for its lifetime.
  • Mistake: Exposing Func<string, T> in a public API. Why it is wrong: callers can't discover valid inputs and tests need to replicate the lambda. Instead: use a typed factory interface.

๐Ÿ› Senior insight: trade-offs

Factories are where DI's automatic lifetime management stops, so the senior part is making ownership explicit in the type system: the factory returns IAsyncDisposable, its own lifetime matches the dependencies it resolves, and run-time arguments are typed (enums, records) rather than strings. Keep the decision logic small; if the factory grows business rules, it's become a strategy resolver and should be tested as one.

Option When it fits Cost When not to
Typed factory + cached ObjectFactory Public API, hot paths One interface and class Single trivial use
Func<T> / Func<TArg, T> Internal, small Opaque, hard to mock clearly Shared libraries
Keyed services Fixed variants, no run-time args Key strings Arguments known only per request
Third-party typed factories (Autofac delegate factories) Already on Autofac Container lock-in Built-in container is enough

Measure with BenchmarkDotNet if the factory is on a hot path, and with dotnet-gcdump if you suspect factory-created objects are leaking.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions Lazy<T> or Func<T> for deferred creation Why: Checks the broader set of factory-injection options and their trade-offs
    How to 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.

  2. When: Candidate talks about disposal of created objects Why: Checks container disposal rules for singleton, scoped and transient services
    How to answer

    The container owns and disposes what it creates. Each scope keeps a list of the IDisposable/IAsyncDisposable objects it built (scoped and transient) and disposes them, in reverse creation order, when the scope ends; singletons are disposed when the root provider is disposed at host shutdown. Instances you pass in with AddSingleton(instance) are not disposed by the container.

    The trap: a transient disposable resolved from the root is tracked by the root, so it lives until shutdown, which is a memory leak if it happens per request. For async: disposing a scope with DisposeAsync calls DisposeAsync on services; calling synchronous Dispose on a scope that holds a service implementing only IAsyncDisposable throws. So use CreateAsyncScope() with await using, and never dispose injected services yourself.

  3. When: Candidate compares this to the Factory Method or Abstract Factory pattern Why: Checks the pattern background and when DI makes a 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.

More in Advanced DI

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me