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.
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 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 youLazy<T>orFunc<T>automatically, unlike Autofac. I register them explicitly, for exampleservices.AddTransient(sp => new Lazy<IPdfRenderer>(sp.GetRequiredService<IPdfRenderer>)). For run-time arguments I prefer a typed factory: anIReportExporterFactorywithCreate(string reportName). Its implementation usesActivatorUtilities.CreateFactoryonce, which returns anObjectFactorydelegate; at call time I pass the report name and it pullsILoggerand the rest from the container. That's much clearer than a rawFunc<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 mustusingit. And if the factory is a singleton holding the rootIServiceProvider, 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."
| 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 |
| 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) |
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.
Checks the candidate can handle run-time arguments and deferred creation with the built-in container without creating captive dependencies or leaks.
Green flags
Func<T>/Lazy<T> aren't automatic in the built-in containerObjectFactoryRed flags
IServiceProvider everywhere and calls GetService with strings of logicLazy<T> to paper over circular dependenciesThe 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
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.
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.
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.
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.
ActivatorUtilities.CreateInstance per call with a cached ObjectFactory over 100,000 creations.Func<IScopedThing>, capture it in a singleton, and check with ValidateScopes whether anything warns you (it won't). Log instance ids across two requests.Func<string, IExporter> with a typed factory and write a unit test with a fake factory.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;
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.IServiceScopeFactory.using/await using at the call site.ActivatorUtilities.CreateInstance on a hot path. Why it is wrong: it reflects every call. Instead: cache an ObjectFactory from CreateFactory.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.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.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.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.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 |
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.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
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.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.
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.
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.
Last updated 23 Nov 2026.