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.
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.
"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,
IReportExporterFactorywithCreate(ReportFormat format, Guid tenantId). Consumers see exactly what they can ask for, and in unit tests I fake it in one line. A registeredFunc<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, likeILogger<CsvExporter>and theDbContext, from the provider. If it's called a lot, I callActivatorUtilities.CreateFactoryonce to get anObjectFactorydelegate 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
ActivatorUtilitiesholding a file stream is the caller's to dispose, so I return it asIDisposableorIAsyncDisposableand callers useawait using. The other mistake is a singleton factory that receives the rootIServiceProviderand builds objects with scoped dependencies from it: thoseDbContexts 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."
| 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 |
| 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 |
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.
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
ActivatorUtilities and knows about cached ObjectFactoryRed flags
IServiceProvider everywhere instead of a factoryMicrosoft.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.
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.
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.
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
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.
ActivatorUtilities.CreateInstance and add a logged Dispose; end the scope and confirm the exporter isn't disposed.ValidateScopes = true and see the exception when it resolves a scoped DbContext.CreateInstance against a cached ObjectFactory with BenchmarkDotNet.string parameters and observe the ambiguity; fix it with a record argument.IReportExporterFactory without any container.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);
});
ActivatorUtilities. Why it is wrong: only container-created objects are tracked. Instead: return IDisposable/IAsyncDisposable and have the caller use using/await using.ValidateScopes throws). Instead: register the factory as scoped.ActivatorUtilities.CreateInstance on a hot path. Why it is wrong: it analyses constructors with reflection every call. Instead: cache an ObjectFactory from CreateFactory.string format, string region). Why it is wrong: ActivatorUtilities matches by type, so it is ambiguous. Instead: wrap them in a record.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.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.
When the container can't build something up front, inject a factory instead of the object.
AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.Func<T> or Lazy<T>; you register them explicitly.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.
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.
switch, that returns the right implementation. It isn't a GoF pattern, but it's fine for a small closed set.DbConnection.CreateCommand() calls the protected abstract CreateDbCommand(), so SqlConnection returns a SqlCommand.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.
Last updated 23 Nov 2026.