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

📚 Interview question

How does the built-in .NET container actually resolve a service? Explain how it chooses a constructor, what call sites are, how ActivatorUtilities differs from GetService, and how the container makes resolution fast after the first call.

Explains resolution in Microsoft.Extensions.DependencyInjection: constructor selection rules, the call-site tree and cache, runtime and compiled resolvers, ActivatorUtilities vs GetService, and what errors you get when resolution fails.

Intermediate Theory Intermediate activatorutilities dependency-injection dotnet-internals performance service-resolution

🎯 Key points

  • Picks the constructor with the most parameters it can satisfy; two satisfiable constructors of the same length throw InvalidOperationException
  • Builds a call-site tree per service type and caches it
  • First resolutions interpret the call site; services resolved repeatedly are compiled in the background to expression-tree or IL resolvers
  • Scoped and singleton call sites cache instances per scope or in the root; resolving scoped from the root makes it a captive singleton
  • GetService returns null for an unregistered type; GetRequiredService throws
  • ActivatorUtilities builds unregistered types and accepts extra run-time arguments; you own their disposal
  • Unresolvable constructor dependency throws InvalidOperationException naming the missing type
  • ValidateOnBuild walks call sites at Build() to fail fast

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Resolution happens in two phases. The first time I ask for a service type, the provider looks up its descriptors and builds a call site, a little tree that says 'construct OrderService with this constructor, whose parameters are the call site for IOrderRepository, which is scoped, and TimeProvider, which is a singleton instance'. Constructor selection is simple: it tries constructors from the most parameters down and picks the longest one where every parameter can be resolved; if two constructors of the same length are both satisfiable it throws rather than guess. Call sites are cached, and lifetimes are just caching rules on top: singletons are stored in the root, scoped instances in the current scope's dictionary, transients are never stored, except for tracking disposables.

The second phase is speed. The provider starts by walking call sites with an interpreter. Once a service has been resolved a couple of times, it compiles the call site in the background into an expression tree or IL delegate, and swaps it in. After that, resolving a transient is basically a delegate call and a new. That's why the built-in container benchmarks well.

ActivatorUtilities is a different tool. GetService only builds things that are registered. ActivatorUtilities.CreateInstance<T>(provider, args) builds a type that isn't registered, matching your explicit arguments to constructor parameters and pulling the rest from the container. The framework uses it for middleware and hosted services. The mistake I see is people adding optional constructors and being surprised which one is chosen, or being surprised that the container won't inject properties. It only does constructors, on purpose."


Constructor selection rules

Situation Result
One public constructor, all parameters resolvable That constructor
Several constructors Longest one whose parameters are all resolvable
Two satisfiable constructors of the same length InvalidOperationException (ambiguous)
Parameter has a default value and isn't registered Default value used
A parameter can't be resolved and has no default InvalidOperationException: Unable to resolve service for type 'X' while attempting to activate 'Y'
ActivatorUtilities with [ActivatorUtilitiesConstructor] That constructor is preferred

GetService vs ActivatorUtilities

GetService / GetRequiredService ActivatorUtilities.CreateInstance
Type must be registered Yes No
Extra run-time arguments No Yes, matched by type
Lifetime managed Yes No; you own and dispose the instance
Typical use Framework resolution, composition root Middleware, factories needing run-time args
Speed Cached compiled call site Reflection each time unless you use CreateFactory

Production example

A team added a second constructor to a repository "for tests" taking a connection string. In production the container started choosing it whenever a string was registered for another reason, and every query hit the wrong database in a staging environment. Removing the extra constructor, and adding a ValidateOnBuild test, made the selection deterministic again.

🔍 What the interviewer is checking

Checks the candidate understands the container's mechanics well enough to predict its behaviour and read its errors.

Green flags

  • States the longest-satisfiable-constructor rule and the ambiguity exception
  • Describes call sites and caching, and lifetimes as caching rules
  • Knows when to use ActivatorUtilities and its disposal implications
  • Mentions ValidateOnBuild to surface errors early

Red flags

  • Thinks the container uses reflection on every resolution
  • Believes property injection works out of the box
  • Has never read an "Unable to resolve service for type" message carefully

📚 Learn in depth

1. From descriptors to call sites

GetService(typeof(OrderService))
   │
   ▼
CallSiteFactory: find descriptor(s) → choose constructor → recurse into parameters
   │
   ▼
ConstructorCallSite(OrderService)
   ├─ ScopedCallSite → ConstructorCallSite(SqlOrderRepository)
   │                     └─ ScopedCallSite → AppDbContext (factory)
   └─ ConstantCallSite(TimeProvider.System)

Call-site kinds include constructor, factory, constant (instance), IEnumerable<T>, IServiceProvider, IServiceScopeFactory and keyed variants. The tree is cached per service identifier.

2. Lifetimes are caching around call sites

  • Singleton: resolved once, stored in the root scope's resolved-services dictionary under a lock.
  • Scoped: stored in the current scope's dictionary. Resolving a scoped service from the root makes it effectively a singleton (that's what ValidateScopes forbids).
  • Transient: never cached, but if it implements IDisposable/IAsyncDisposable the scope keeps a reference so it can dispose it.

3. Interpreted, then compiled

resolution 1..n  → CallSiteRuntimeResolver (walks the tree)
after threshold  → background compile → ExpressionResolverBuilder / ILEmitResolverBuilder
later calls      → cached Func<ServiceProviderEngineScope, object>

On platforms without dynamic code (Native AOT, RuntimeFeature.IsDynamicCodeSupported == false) it stays with the runtime resolver, which is slower per call but still fine for most apps.

4. Constructor selection in detail

The provider sorts public constructors by parameter count, descending. For each, it checks whether every parameter has a call site or a default value. The first fully satisfiable one wins, unless another constructor with the same count is also satisfiable, which throws. It never uses non-public constructors and never sets properties.

5. ActivatorUtilities

CreateInstance(provider, type, params object[] args) scores constructors by how many explicit arguments it can match by type, fills the rest from provider, and honours [ActivatorUtilitiesConstructor]. ActivatorUtilities.CreateFactory(type, argumentTypes) returns an ObjectFactory delegate you can cache, avoiding reflection per call. ASP.NET Core uses it for convention-based middleware and UseMiddleware<T>(args).

Try it yourself

  1. Give a class two constructors of the same length with resolvable parameters and watch resolution throw.
  2. Add a constructor parameter with a default value that isn't registered; confirm the default is used.
  3. BenchmarkDotNet: resolve a transient 1 and 10,000 times; compare first-call vs steady-state cost.
  4. Build an unregistered ReportGenerator(string reportName, ILogger<ReportGenerator> logger) with ActivatorUtilities.CreateInstance, then with a cached CreateFactory.
  5. Turn on ValidateOnBuild and remove a registration; read the exception message at Build().

💻 Code

Constructor selection and ActivatorUtilities in a console app.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var services = new ServiceCollection()
    .AddLogging()
    .AddSingleton(TimeProvider.System)
    .AddTransient<InvoiceService>();

using var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
    ValidateScopes = true,
    ValidateOnBuild = true // walks every call site now, not on first request
});

// Registered type: the container picks the longest satisfiable constructor.
var invoices = provider.GetRequiredService<InvoiceService>();

// Unregistered type with a run-time argument: ActivatorUtilities fills the rest.
var report = ActivatorUtilities.CreateInstance<ReportGenerator>(provider, "monthly-gst");
Console.WriteLine(report.Describe());

// Hot path: build the factory once and reuse it (no reflection per call).
ObjectFactory factory = ActivatorUtilities.CreateFactory(typeof(ReportGenerator), [typeof(string)]);
var quarterly = (ReportGenerator)factory(provider, ["quarterly-bas"]);

public sealed class InvoiceService
{
    public InvoiceService(TimeProvider clock) { }

    // Chosen: both parameters resolvable and it is longer.
    public InvoiceService(TimeProvider clock, ILogger<InvoiceService> logger) { }
}

public sealed class ReportGenerator(string reportName, ILogger<ReportGenerator> logger)
{
    public string Describe()
    {
        logger.LogInformation("Building {Report}", reportName);
        return $"Report: {reportName}";
    }
}

⚠ Common mistakes

  • Mistake: Adding extra public constructors "for tests". Why it is wrong: the container may pick a different constructor when registrations change, or throw on ambiguity. Instead: keep one public constructor; tests can call it directly.
  • Mistake: Expecting property injection with the built-in container. Why it is wrong: it only uses constructors. Instead: use constructor parameters, or a container like Autofac if you really need properties.
  • Mistake: Using ActivatorUtilities.CreateInstance in a hot loop. Why it is wrong: it reflects over constructors on each call. Instead: cache an ObjectFactory from CreateFactory.
  • Mistake: Assuming instances from ActivatorUtilities are disposed by the container. Why it is wrong: they aren't tracked. Instead: dispose them yourself or register the type.
  • Mistake: Discovering missing registrations only when an endpoint is first hit. Why it is wrong: call sites are built lazily. Instead: enable ValidateOnBuild (and a test that builds the host).
  • Mistake: Measuring container cost from the first resolution. Why it is wrong: the first calls are interpreted and include call-site building. Instead: benchmark steady state with BenchmarkDotNet.

🏛 Senior insight: trade-offs

Knowing the internals matters mostly for two things: diagnosing the exception messages quickly, and not over-thinking container performance. After warm-up, resolution is a cached delegate; your database call is a million times slower. The things that do cost are start-up work (call-site building for thousands of services, assembly scanning) and per-request allocations of large transient graphs.

Tool When it fits Cost When not to
Constructor injection via container Almost everything Negligible after warm-up Objects needing run-time data
ActivatorUtilities.CreateInstance Occasional unregistered types with run-time args Reflection per call Hot paths
ActivatorUtilities.CreateFactory Repeated creation with run-time args One-off reflection When a simple factory delegate would do
Manual new in a factory Tiny objects with known dependencies None When dependencies change often

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions primary constructors or constructor overloads Why: Checks constructor mechanics that interact with DI selection
    How to answer

    A constructor runs when an object is created and should leave it valid. If you declare none, the compiler adds a public parameterless one. Constructors can chain: : this(...) calls another constructor of the same class, : base(...) calls the base class's. For new Derived(), the order is: derived field initialisers, base field initialisers, base constructor body, derived constructor body. A static constructor runs once, before the type is first used, and is thread-safe. Primary constructors (C# 12) put parameters on the class declaration; they are captured as hidden fields, not properties, and are mutable. required members (C# 11) force callers to set them in an object initialiser. Calling a virtual method from a constructor runs the derived override before the derived constructor body has run, so it can see uninitialised state.

  2. When: Candidate uses primary constructors for injected services Why: Checks the parameter-capture pitfalls of primary constructors with DI
    How to answer

    On a record, primary constructor parameters become public init properties. On a class or struct (C# 12) they are just parameters in scope for the whole type body: no property is generated. If a member uses one, the compiler captures it into a hidden mutable field. That causes three review issues: captured parameters are mutable (no readonly), using a parameter both to initialise a field or property and directly in a member stores it twice (warning CS9124, which can lead to stale values), and passing a parameter to the base constructor and also capturing it gives CS9107. They are great for dependency injection of services. For values needing validation or a read-only guarantee, assign them to an explicit readonly field or property in an initialiser.

  3. When: Candidate mentions failing fast on missing registrations Why: Checks the limits of container validation
    How to answer

    ValidateOnBuild makes Build() walk every registration and try to build its call site, so a missing dependency or an unresolvable constructor fails at start-up instead of on the first request that needs it. Combined with ValidateScopes it also catches a singleton depending on a scoped service.

    What it cannot catch:

    • anything inside a factory delegate (sp => ...): the body is opaque code that only runs on resolution;
    • open generics, which can't be checked until a closed type is requested;
    • types created later with ActivatorUtilities.CreateInstance or GetService calls in your own code.

    ASP.NET Core's WebApplication turns it on only in the Development environment; enable it everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }). The start-up cost is a one-off graph walk, typically small, and it buys you a fast failure in every environment.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me