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.
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.
"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
OrderServicewith this constructor, whose parameters are the call site forIOrderRepository, which is scoped, andTimeProvider, 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.
ActivatorUtilitiesis a different tool.GetServiceonly 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."
| 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 / 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 |
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.
Checks the candidate understands the container's mechanics well enough to predict its behaviour and read its errors.
Green flags
ActivatorUtilities and its disposal implicationsValidateOnBuild to surface errors earlyRed flags
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.
ValidateScopes forbids).IDisposable/IAsyncDisposable the scope keeps a reference so it can dispose it.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.
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.
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).
ReportGenerator(string reportName, ILogger<ReportGenerator> logger) with ActivatorUtilities.CreateInstance, then with a cached CreateFactory.ValidateOnBuild and remove a registration; read the exception message at Build().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}";
}
}
ActivatorUtilities.CreateInstance in a hot loop. Why it is wrong: it reflects over constructors on each call. Instead: cache an ObjectFactory from CreateFactory.ActivatorUtilities are disposed by the container. Why it is wrong: they aren't tracked. Instead: dispose them yourself or register the type.ValidateOnBuild (and a test that builds the host).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 |
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.
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.
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:
sp => ...): the body is opaque code that only runs on resolution;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.
Last updated 23 Nov 2026.