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

📚 Interview question

What does dependency injection cost at run time in .NET, and how does Microsoft.Extensions.DependencyInjection behave under Native AOT and trimming? Explain how the container resolves services fast after the first call, where start-up cost comes from, which registration styles produce trimming warnings, what source-generated containers offer, and when any of this actually matters.

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.

Senior Theory Advanced dependency-injection native-aot performance startup-time trimming

🎯 Key points

  • Each service's call site is built once and cached; with JIT the engine compiles a resolver delegate after a couple of resolutions
  • Under Native AOT the container keeps the same behaviour and cached call sites but interprets them instead of compiling: correct, slightly slower per resolution
  • Per-resolution cost is tens of nanoseconds; in most APIs I/O dominates latency, and the container's main steady-state cost is the allocations of transient and scoped objects
  • Lifetimes are the performance lever: thread-safe stateless services as singletons cut per-request allocations and GC pressure
  • Start-up cost comes from registration volume, assembly scanning, ValidateOnBuild and heavy singleton constructors
  • Generic AddTransient<TService, TImpl>() and typeof registrations are annotated so the trimmer keeps constructors; reflection scanning triggers IL2026/IL2072 warnings
  • Value-type closed generics and IEnumerable of value types can need code AOT didn't generate; source-generated containers (Jab, Pure.DI) avoid reflection but lose MS.DI integration
  • Measure in the real app first (dotnet-trace for start-up, dotnet-counters for allocation rate, BenchmarkDotNet for resolution) before changing DI design

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 new calls. 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>() carry DynamicallyAccessedMembers annotations, so the trimmer keeps the constructor. Assembly scanning with Assembly.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."


Where the time goes

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

Registration styles and trimming/AOT

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains call-site caching and compiled resolvers versus the AOT interpreter
  • Puts numbers on resolution cost and points at start-up and allocations instead
  • Knows which registration styles are trim/AOT-safe and why scanning isn't
  • Mentions source-generated containers with their trade-off, and measures first

Red flags

  • Claims DI uses reflection on every resolution
  • Thinks the built-in container doesn't work with Native AOT at all
  • Proposes replacing the container without measurements

📚 Learn in depth

1. Call sites

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)

2. Engines

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.

3. Start-up

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().

4. Trimming and AOT

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.

5. Source-generated containers

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.

Try it yourself

  1. BenchmarkDotNet: resolve a singleton, a scoped and a transient service with three dependencies 1,000,000 times; compare with new.
  2. Resolve a service once, twice and three times while profiling with dotnet-trace to see the switch to the compiled resolver.
  3. Publish a minimal API with PublishAot=true and Scrutor scanning; read the warnings, then replace scanning with explicit registrations.
  4. Register an open generic, resolve it with a value-type argument in an AOT build and observe the behaviour.
  5. Time builder.Build() with and without ValidateOnBuild for a project with a few hundred registrations.

💻 Code

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>();
}

⚠ Common mistakes

  • Mistake: Blaming the DI container for request latency without measuring. Why it is wrong: steady-state resolution is nanoseconds; I/O and allocations dominate. Instead: profile with dotnet-trace or Application Insights before optimising DI.
  • Mistake: Using reflection-based assembly scanning in a Native AOT or trimmed app. Why it is wrong: it produces IL2026 warnings and trimmed types fail at run time. Instead: register explicitly or use a source generator.
  • Mistake: Ignoring trimming warnings. Why it is wrong: they describe real run-time failures. Instead: treat them as errors in AOT projects.
  • Mistake: Closing open generics over value types in an AOT app. Why it is wrong: the required instantiation may not exist, and resolution throws. Instead: use reference types or closed registrations.
  • Mistake: Doing heavy work in singleton constructors. Why it is wrong: it runs on first resolution, often on a request thread, and shows up as a slow first request. Instead: warm up in an IHostedService or make the work lazy and asynchronous.
  • Mistake: Switching to a source-generated container for speed alone. Why it is wrong: the gain is usually negligible outside cold starts, and you lose IServiceCollection integration. Instead: adopt one only for AOT or measured cold-start problems.
  • Mistake: Registering hundreds of transients that allocate per request in a hot path. Why it is wrong: GC pressure grows with throughput. Instead: make stateless services singletons when thread-safe, and measure allocations with [MemoryDiagnoser].

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions call sites or compiled resolvers Why: Checks how the built-in container resolves services in detail
    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.

  2. When: Candidate mentions source generators for AOT Why: Checks knowledge of the source generators that ship with .NET 10
    How to answer

    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.

  3. When: Candidate mentions assembly scanning and start-up cost Why: Checks how they organise registrations in a large solution
    How to answer

    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.

🛠 Real-world problems: how you handle them

Native AOT publish trimmed a scanned handler away
Situation
A [queue-triggered order processor] on .NET [10] running as an Azure Function (isolated worker) in [Australia East] had cold starts of about [1.4] s, which caused queue backlogs during scale-out. The team published it with Native AOT. Handlers were registered by scanning the assembly for `IOrderHandler` implementations.
Signals
The AOT build produced about [30] IL2026/IL2072 warnings that nobody read. After deployment, cold start dropped, but `CancelOrder` messages went to the poison queue with `InvalidOperationException: No handler registered for CancelOrderMessage`; Application Insights showed the failure rate for that message type at 100%.
Investigation
Reproduced locally by running the AOT binary. Read the trimming warnings and found they all pointed to the scanning code. Checked the published binary's handler list by logging resolved `IEnumerable<IOrderHandler>` at start-up: `CancelOrderHandler` was missing because nothing referenced it statically.
Resolution
Immediate: redeployed the previous JIT build and replayed the poison queue. Fix: replaced scanning with explicit `AddScoped<IOrderHandler, ...>()` registrations generated from a checked-in list, set `TreatWarningsAsErrors` in the project, and republished with AOT.
Prevention
Trimming warnings fail the build; a start-up self-check logs and asserts the expected handler count; an AOT smoke test in CI publishes the binary and processes one message of each type.

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.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me