Performance and Native AOT for the built-in DI container: call-site caching, the switch from the reflection-based runtime resolver to compiled resolvers under JIT, the interpreter used under Native AOT, start-up costs (registration volume, scanning, ValidateOnBuild), trimming annotations and warnings, value-type generic limits, source-generated containers and when DI cost matters.
The built-in container is fast after the first resolution: it builds a call site per service once, caches it and, on a JIT runtime, compiles a resolver delegate after a couple of calls, so a resolution costs tens of nanoseconds. Under Native AOT there's no dynamic code, so it interprets the cached call sites, which is still correct and only slightly slower. The real costs are elsewhere: start-up (thousands of registrations, assembly scanning, ValidateOnBuild, eager singletons) and allocations from transient-heavy graphs. For trimming, generic AddScoped<TService, TImpl>() is annotated so constructors survive, while reflection-based scanning produces IL2026 warnings and can lose types. Source-generated containers remove run-time reflection entirely but lose ecosystem integration. It matters for cold starts, CLIs and AOT; elsewhere the database dwarfs it.
"Most of the time, DI isn't where your latency goes. The container builds a call site the first time a service is requested, an object describing how to construct it, and caches it. On a normal JIT runtime the engine starts by walking that call site with a reflection-based resolver, and after a service has been resolved a couple of times it compiles a delegate in the background, with IL emit, so later resolutions are close to hand-written
newcalls. A singleton lookup is a few nanoseconds of dictionary work; a transient with a handful of dependencies is tens of nanoseconds plus the allocations.Native AOT changes the engine, not the behaviour. There's no JIT, so the container can't emit code; it uses the runtime resolver that interprets the cached call sites. That's slower per resolution but still small. What does break under AOT and trimming is reflection you add yourself. Generic registrations like
AddScoped<IOrderService, OrderService>()carryDynamicallyAccessedMembersannotations, so the trimmer keeps the constructor. Assembly scanning withAssembly.GetTypes()can't be analysed, so you get IL2026 warnings and, worse, types that silently disappear. Open generics closed over value types can also need code the AOT compiler never generated.For example, at [company] we [moved a queue-triggered function to Native AOT to cut cold starts]. The build produced [about 30] trimming warnings from Scrutor scanning, and one handler was trimmed away and failed at run time. We [replaced scanning with explicit registrations]; [cold start went from about 1.4 s to 300 ms]. The mistake I see is optimising the container before measuring: in a typical API the first thing to fix is the database call, not resolution. The senior point is knowing where DI cost is real: start-up, cold starts and AOT compatibility."
| Phase | Cost driver | Typical size |
|---|---|---|
| Registration | Number of Add* calls; scanning with reflection |
Microseconds per explicit call; scanning can take 100s of ms |
Build() |
ValidateOnBuild walks every descriptor |
10s–100s of ms for large apps |
| First resolution per service | Building and validating the call site | Microseconds per service |
| Steady-state resolution | Compiled delegate (JIT) or interpreter (AOT) | Nanoseconds to tens of nanoseconds |
| Allocation | Transient and scoped instances per request | Often the biggest steady-state cost |
| Style | Trim/AOT behaviour |
|---|---|
AddScoped<IService, Impl>() |
Safe: constructor kept via annotations |
AddScoped(typeof(IService), typeof(Impl)) |
Safe when types are statically known |
Factory sp => new Impl(...) |
Safe: no reflection |
| Open generics over reference types | Generally safe |
Open generics or IEnumerable<T> over value types |
May fail at run time under AOT |
Reflection scanning (Assembly.GetTypes, Scrutor) |
Warnings (IL2026/IL2072); types can be trimmed |
On a [queue-triggered Azure Function], switching to Native AOT with explicit registrations cut cold start from about 1.4 s to 300 ms and memory from about 120 MB to 45 MB per instance. Steady-state throughput barely changed, which matched our BenchmarkDotNet run showing resolution under 1% of handler time.
Checks whether the candidate understands how the container achieves fast resolution, where real DI costs lie, and what Native AOT and trimming require of registrations.
Green flags
Red flags
A call site is a tree describing how to build a service: ConstructorCallSite (with parameter call sites), FactoryCallSite, ConstantCallSite, IEnumerableCallSite, and wrappers for lifetime caching. CallSiteFactory builds them on demand and caches them by service identifier.
OrderService (Scoped)
ConstructorCallSite
IOrderRepository (Scoped) -> ConstructorCallSite -> AppDbContext (Scoped)
TimeProvider (Singleton) -> ConstantCallSite
ILogger<OrderService> -> ConstructorCallSite (open generic closed)
RuntimeFeature.IsDynamicCodeCompiled ?
DynamicServiceProviderEngine:
first calls -> CallSiteRuntimeResolver (walks the tree with reflection invoke)
after ~2 calls -> background compile (ILEmitResolverBuilder) -> Func<ServiceProviderEngineScope, object>
: RuntimeServiceProviderEngine (Native AOT):
always CallSiteRuntimeResolver
The realised delegate is stored per service, so steady-state resolution is a dictionary lookup plus the delegate call. Singletons are cached in the root scope; scoped instances in the scope's ResolvedServices dictionary (with a lock); transient disposables are added to the scope's disposables list.
Start-up cost scales with: registration count (cheap individually), reflection scanning (expensive: loads and inspects every type), ValidateOnBuild (builds call sites for every descriptor), and singletons that do work in constructors when first resolved. Measure with dotnet-trace collect --providers Microsoft-Extensions-DependencyInjection and a stopwatch around builder.Build().
The trimmer removes code it can't prove is used. Generic registration methods annotate the implementation type parameter with [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)], telling the trimmer to keep constructors. Scanning code calls Assembly.GetTypes(), marked [RequiresUnreferencedCode], which produces IL2026 and makes any type found only that way a candidate for removal.
Native AOT also needs every generic instantiation to exist at compile time. Reference-type instantiations can share canonical code; value-type instantiations (IRepository<int>, IEnumerable<SomeStruct>) need specialised code, and the DI library guards against creating them dynamically under AOT, throwing instead.
Generators such as Jab or Pure.DI read registrations declared with attributes or a DSL and emit the construction code at compile time: no reflection, errors at build time, AOT-friendly. The trade-off: ASP.NET Core and most libraries register into IServiceCollection, so you end up bridging two containers or limiting the generator to your own services.
new.dotnet-trace to see the switch to the compiled resolver.PublishAot=true and Scrutor scanning; read the warnings, then replace scanning with explicit registrations.builder.Build() with and without ValidateOnBuild for a project with a few hundred registrations.AOT-friendly registrations versus reflection scanning, plus a benchmark harness (.NET 10, BenchmarkDotNet):
<!-- Orders.Api.csproj -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PublishAot>true</PublishAot>
<!-- Make trimming/AOT warnings fail the build so problems can't ship silently. -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
using Microsoft.Extensions.DependencyInjection;
namespace Orders.Api;
public interface IOrderHandler { Task HandleAsync(OrderMessage message, CancellationToken ct); }
public sealed record OrderMessage(Guid OrderId);
public sealed class PlaceOrderHandler(TimeProvider clock) : IOrderHandler
{
public Task HandleAsync(OrderMessage message, CancellationToken ct) => Task.CompletedTask;
}
public static class Registration
{
public static IServiceCollection AddOrderHandlers(this IServiceCollection services)
{
services.AddSingleton(TimeProvider.System);
// AOT/trim-safe: the generic parameter is annotated, so the constructor is preserved.
services.AddScoped<IOrderHandler, PlaceOrderHandler>();
// NOT AOT-safe: reflection discovery produces IL2026 and can lose trimmed types.
// foreach (var t in typeof(Registration).Assembly.GetTypes()
// .Where(t => t.IsAssignableTo(typeof(IOrderHandler)) && !t.IsAbstract))
// services.AddScoped(typeof(IOrderHandler), t);
return services;
}
}
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
namespace Orders.Benchmarks;
[MemoryDiagnoser]
public class ResolutionBenchmarks
{
private IServiceScope _scope = null!;
[GlobalSetup]
public void Setup()
{
var provider = new ServiceCollection().AddOrderHandlers().BuildServiceProvider();
_scope = provider.CreateScope();
_scope.ServiceProvider.GetRequiredService<IOrderHandler>(); // warm the call site
}
[Benchmark(Baseline = true)]
public IOrderHandler New() => new PlaceOrderHandler(TimeProvider.System);
[Benchmark]
public IOrderHandler Resolve() => _scope.ServiceProvider.GetRequiredService<IOrderHandler>();
}
IHostedService or make the work lazy and asynchronous.IServiceCollection integration. Instead: adopt one only for AOT or measured cold-start problems.[MemoryDiagnoser].DI performance is mostly a start-up and deployment-model question, not a steady-state one. In a long-running API, the container's cost disappears next to I/O; in serverless functions, CLIs and Native AOT apps, start-up and trim-compatibility decide the design. The senior answer is to measure first and know which registration styles are AOT-safe, so you don't paint yourself into a corner before a cold-start target arrives.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Built-in container, explicit registrations | Default, including AOT | More lines | Never wrong |
| Built-in + reflection scanning | Large JIT apps, uniform types | Start-up time; not AOT-safe | AOT, cold-start-sensitive |
| Source-generated container | AOT with very large graphs, build-time errors wanted | Ecosystem bridging | Typical ASP.NET Core apps |
| Lifetime tuning (transient → singleton) | Measured allocation hot spots | Thread-safety review | Stateful services |
Measure with BenchmarkDotNet for resolution, dotnet-counters (allocation rate, GC count) for steady state, and a stopwatch or dotnet-trace for start-up.
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.
A source generator is a compiler plug-in that reads your code (usually a marker attribute on a partial declaration) and adds new C# files to the compilation; it can never change or delete your code. .NET ships several: System.Text.Json ([JsonSerializable] on a JsonSerializerContext) for reflection-free serialisation, [GeneratedRegex] for regex compiled to C# at build time, [LoggerMessage] for allocation-free structured logging, [LibraryImport] for P/Invoke marshalling, and in ASP.NET Core the configuration binding and Request Delegate generators that replace reflection in Bind/Get<T> and minimal APIs. They improve startup, cut allocations and make code trim and Native AOT safe. Inspect output under Dependencies, Analyzers in the IDE, or set EmitCompilerGeneratedFiles to write the files to obj.
I make each module own its wiring: a public AddOrdersModule(this IServiceCollection, IConfiguration) extension next to internal implementations, so Program.cs becomes a short list of module calls that reads like the architecture. Shared infrastructure (clock, caching, messaging) is registered with TryAdd so modules don't depend on call order or duplicate it. For registration style, explicit registrations are clear, fast and Native AOT-safe; assembly scanning with Scrutor saves lines for dozens of handlers but costs start-up reflection, breaks trimming and can register things you didn't mean to, so I scope it to marker interfaces. Then I test the composition root: build the production host with ValidateOnBuild and ValidateScopes, resolve factory and open-generic services, and add architecture tests so modules can't reach into each other's internals.
How to tell it (STAR)
**S:** [Our order processor function] had cold starts of [about 1.4 seconds], so we moved it to Native AOT. **T:** After the release, every cancel message failed, and I had to restore processing and make AOT safe for us. **A:** I rolled back to the JIT build and replayed the poison queue first. Running the AOT binary locally showed the cancel handler wasn't registered: our assembly scanning used reflection, the trimmer had removed a handler nothing referenced directly, and the build had warned us [30] times. I replaced scanning with explicit registrations, made trimming warnings fail the build, and added a CI smoke test that processes one message of every type with the AOT binary. **R:** The AOT version went back out the next day with cold starts of [about 300 ms], no lost messages, and the smoke test has caught [one] more trimming issue since.
Last updated 23 Nov 2026.