DI: (opt) ILEmit resolvers re-take the scope lock for nested scoped services and use interface dispatch on the scope cache
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 12/100
- Issue type
- Refactor
- Clarity
- Clearly specified
- Activity status
- Active
- Tech stack
- csharp
- Domain
- performance
Research direction
Start in src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs: read GenerateMethodBody for the Monitor.Enter/Exit prologue and the TryGetValue/Add callvirt sites, then ILEmitResolverBuilderRuntimeContext and ExpressionResolverBuilder where the shared MethodInfos are consumed. The proposed change is three independent pieces — the ScopeLockHeld context flag, direct Dictionary<ServiceCacheKey, object?> calls, and ldnull for a null ServiceKey — and the issue suggests landing the latter two separately. Done means existing DI tests under src/libraries/Microsoft.Extensions.DependencyInjection/tests pass plus a benchmark showing the recursive lock gone for nested scoped graphs.
Written by the indexing model from the issue text.
Description
Problem
In OrchardCore on Cobalt 200, Microsoft.Extensions.DependencyInjection machinery (excluding the services' own constructors) is about 11.7% of CPU:
| Symbol | % of cycles |
|---|---|
Dictionary<ServiceCacheKey, object>.TryGetValue/Add/Resize |
~2.9% |
dynamicClass::ResolveService (bodies) |
2.0% |
Monitor.Exit |
1.57% |
Monitor.Enter |
1.01% |
ObjectHeader.TryAcquireUncommon (recursive thin-lock path) |
0.79% |
CastHelpers.StelemRef_Helper (IEnumerable arrays) |
0.30% |
VSD dispatch stubs called from ResolveService |
0.19% |
Three inefficiencies in the code emitted by ILEmitResolverBuilder for scope-cached call sites:
- Recursive scope locking. Every scoped resolver does
Monitor.Enter(scope.Sync)and builds the service while holding the lock. A scoped dependency of a scoped service is resolved by calling the dependency'sDynamicMethod, which takes the same lock again (a recursive thin lock: CAS inTryAcquireUncommonplus CAS inExit). Deep scoped graphs re-enter the lock once per level.CallSiteRuntimeResolveralready avoids this withRuntimeResolverLock/AcquiredLocks; the ILEmit path doesn't. On arm64 each of these CASes is acasal, andMonitor.Exitspends 83% of its samples on it. - Interface dispatch on the cache. The emitted code calls
TryGetValue/AddthroughIDictionary<ServiceCacheKey, object>, so each scoped resolve does two VSD interface calls.ResolvedServicesis always aDictionary<ServiceCacheKey, object?>, so the calls can be direct (andTryGetValuegets inlined into the dynamic method). - Null service key loaded from the constants array. The cache key is built with
AddConstant(id.ServiceKey)even when the key isnull(the common, non-keyed case). That's a dependent load chain (context ->Constantsarray -> bounds check -> element) on every resolve; in the hottestResolveServiceinstances ~40% of samples sat on that length load/bounds check (some of it likely skid from the prologue).
Proposal
- Track at emit time whether code runs under the scope lock (
ILEmitResolverBuilderContext.InScopeLock, set while emitting the creation of a scope-cached service). Each scope-cachedGeneratedMethodgets a second runtime context instance that is identical except forScopeLockHeld = true. Nested calls emitted under the lock pass that context, and the emitted prologue skipsMonitor.Enterwhencontext.ScopeLockHeldis set. That's one field load and a branch, no extra call, no extra dynamic methods, and the same "take the lock once per resolution chain" semantics asCallSiteRuntimeResolver. Nested calls always pass the samescopeargument (ldarg.1), so the caller does hold that scope's lock. - Use
Dictionary<ServiceCacheKey, object?>.TryGetValue/Addviacall(also for the expression-tree builder, which shares theMethodInfos). - Emit
ldnullwhenServiceKeyis null.
An earlier variant used Monitor.IsEntered(sync) instead of the context flag; it was slightly slower for non-nested resolution because of the extra call, so I went with the emit-time approach.
Invariants the lock elision relies on:
- Nested scoped resolvers are only reached through direct, synchronous emitted calls that forward the caller's own
ldarg.1, so the callee's scope is exactly the scope whose lock the caller holds. - The
IsRootScopebranch runs before the skip, and the delegate returned byBuild(used byServiceProvider.GetService) stays bound to the unlocked context. finallyonly callsMonitor.Exitwhen the current invocation took the lock.- Singleton dependencies are resolved at emit time (
VisitRootCache), and factories re-enter through the provider, which uses the unlocked context. So factories keep today's (recursive) locking.
For (2), changing only the opcode isn't enough: the receiver must be typed as Dictionary<ServiceCacheKey, object> everywhere the shared MethodInfos are used, i.e. resolvedServicesLocal in ILEmitResolverBuilder.GenerateMethodBody and the ResolvedServices ParameterExpression in ExpressionResolverBuilder (otherwise Expression.Call throws). (2) and (3) are independent of (1) and could go in a separate, trivial PR.
Core of the change:
private sealed class ILEmitResolverBuilderRuntimeContext
{
public object?[]? Constants;
public Func<IServiceProvider, object>[]? Factories;
+ // True for the context passed by resolvers that already hold the scope lock.
+ public bool ScopeLockHeld;
}
...
- AddConstant(argument, generatedMethod.Context);
+ // When called under the scope lock (from another scoped resolver), let the callee skip taking it again.
+ AddConstant(argument, argument.InScopeLock ? generatedMethod.ScopeLockHeldContext : generatedMethod.Context);
...
+ // Skip Monitor.Enter if the caller already holds the scope lock (nested scoped resolution)
+ context.Generator.Emit(OpCodes.Ldarg_0);
+ context.Generator.Emit(OpCodes.Ldfld, ScopeLockHeldField);
+ context.Generator.Emit(OpCodes.Brtrue, lockHeldLabel);
...Monitor.Enter(sync, ref lockTaken)...
+ context.Generator.MarkLabel(lockHeldLabel);
...
- context.Generator.Emit(OpCodes.Callvirt, ServiceLookupHelpers.TryGetValueMethodInfo);
+ context.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.TryGetValueMethodInfo);
...
+ context.InScopeLock = true;
VisitCallSiteMain(callSite, context);
+ context.InScopeLock = false;
Measurements (Cobalt 200, linux-arm64)
Microbenchmark: one scope per iteration, resolving a root scoped service with a 6-level scoped dependency graph (plus a disposable and an IEnumerable<IDep>), then 4 cached lookups. "Flat" resolves 5 independent scoped services twice each.
public sealed class D0 : IDep { }
public sealed class D1 : IDep { public D1(D0 d) { } }
public sealed class D2 : IDep { public D2(D0 a, D1 b) { } }
public sealed class D3 : IDep { public D3(D1 a, D2 b) { } }
public sealed class D4 : IDep { public D4(D2 a, D3 b, D0 c) { } }
public sealed class D5 : IDep { public D5(D4 a, D3 b) { } }
public sealed class Disp : IDisposable { public Disp(D5 d) { } public void Dispose() { } }
public sealed class Root { public Root(D5 a, D4 b, Disp c, IEnumerable<IDep> all) { } }
static void Run(IServiceProvider sp) {
using var scope = sp.CreateScope();
var p = scope.ServiceProvider;
p.GetService(typeof(Root));
p.GetService(typeof(D3)); p.GetService(typeof(D4)); p.GetService(typeof(D5)); p.GetService(typeof(D1));
}
| Baseline (main) | Patched | ||
|---|---|---|---|
| nested | 0.80 M scopes/s | 1.10 M scopes/s | +37% |
| flat | ~1.94 M scopes/s | ~1.98 M scopes/s | neutral |
OrchardCore /about (6 runs each, 3 processes, rotated order): +1.9% RPS (27,282 -> 27,803). In the profile TryAcquireUncommon disappears and Monitor.Exit drops from 1.57% to 0.90%.
Notes
CaptureDisposablestill doeslock (Sync)while the scope lock is already held (recursive), but it was only ~0.09% here.- The remaining DI cost is mostly memory latency in
Dictionary<ServiceCacheKey, object>.FindValue(the per-request scope cache) and the non-nestedMonitor.Enter/Exitpair.
[!NOTE]
This issue was drafted with the help of GitHub Copilot.
- Dominant language
- C#
- Stars
- 18.5k
- Forks
- 5.8k
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 588
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/runtime
-
area-CodeGen-coreclr untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
dotnet/runtime#138181 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Collections untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
dotnet/runtime#138090 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Text.Json untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
dotnet/runtime#138089 · 1 comment ·
Maintainers usually reply within 1 day
-
area-Setup untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
dotnet/runtime#137376 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Memory untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
dotnet/runtime#137334 · 4 comments ·
Maintainers usually reply within 1 day
Similar issues
-
Add `net10.0`Open
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
dotnet-outdated/dotnet-outdated#871 ·
Maintainers usually reply within 1 day
-
triage/untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
unoplatform/uno#26676 ·
Maintainers usually reply within 1 day
-
.NET bug
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
jhaizhou-ops/S2Arm#2177 · 3 comments ·
Maintainers usually reply within 1 day