DI: (opt) ILEmit resolvers re-take the scope lock for nested scoped services and use interface dispatch on the scope cache

Open
#138,010 2 comments 0 reactions 0 assignees View on GitHub

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

area-Extensions-DependencyInjection

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:

  1. 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's DynamicMethod, which takes the same lock again (a recursive thin lock: CAS in TryAcquireUncommon plus CAS in Exit). Deep scoped graphs re-enter the lock once per level. CallSiteRuntimeResolver already avoids this with RuntimeResolverLock/AcquiredLocks; the ILEmit path doesn't. On arm64 each of these CASes is a casal, and Monitor.Exit spends 83% of its samples on it.
  2. Interface dispatch on the cache. The emitted code calls TryGetValue/Add through IDictionary<ServiceCacheKey, object>, so each scoped resolve does two VSD interface calls. ResolvedServices is always a Dictionary<ServiceCacheKey, object?>, so the calls can be direct (and TryGetValue gets inlined into the dynamic method).
  3. Null service key loaded from the constants array. The cache key is built with AddConstant(id.ServiceKey) even when the key is null (the common, non-keyed case). That's a dependent load chain (context -> Constants array -> bounds check -> element) on every resolve; in the hottest ResolveService instances ~40% of samples sat on that length load/bounds check (some of it likely skid from the prologue).

Proposal

  1. 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-cached GeneratedMethod gets a second runtime context instance that is identical except for ScopeLockHeld = true. Nested calls emitted under the lock pass that context, and the emitted prologue skips Monitor.Enter when context.ScopeLockHeld is 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 as CallSiteRuntimeResolver. Nested calls always pass the same scope argument (ldarg.1), so the caller does hold that scope's lock.
  2. Use Dictionary<ServiceCacheKey, object?>.TryGetValue/Add via call (also for the expression-tree builder, which shares the MethodInfos).
  3. Emit ldnull when ServiceKey is 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 IsRootScope branch runs before the skip, and the delegate returned by Build (used by ServiceProvider.GetService) stays bound to the unlocked context.
  • finally only calls Monitor.Exit when 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

  • CaptureDisposable still does lock (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-nested Monitor.Enter/Exit pair.

[!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

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.