Skip to content

Avoid resolving the default IHubActivator from DI on every hub invocation - #70141

Open
davidfowl wants to merge 5 commits into
mainfrom
perf/signalr-hub-activator
Open

davidfowl wants to merge 5 commits into
mainfrom
perf/signalr-hub-activator

Conversation

@davidfowl

Copy link
Copy Markdown
Member

Avoid resolving the default IHubActivator from DI on every hub invocation

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. No issue; this is a perf improvement found by profiling.

Skip DI resolution of the default IHubActivator<THub> on each hub invocation.

Description

DefaultHubDispatcher resolves the scoped IHubActivator<THub> from a new service scope for every invocation, plus OnConnectedAsync, OnDisconnectedAsync and OnAuthenticationRefreshedAsync. When the scope resolves its first scoped service, its resolved-services dictionary grows. That growth and the DI lookup together cost about 184 B and 55 ns per invocation. I measured this separately: the scope alone is 128 B, the scope plus the activator is 344 B, and the activator itself is only a 32 B object.

The built-in DefaultHubActivator<THub> is internal, sealed and not disposable. Its only state is the scoped IServiceProvider. With this change, the dispatcher resolves the activator from DI the first time, as before, and records whether the container produced DefaultHubActivator<THub>. If it did, later calls construct new DefaultHubActivator<THub>(scope.ServiceProvider) directly. The scoped provider is the same one, so hub construction, scoped dependencies, Release and disposal semantics don't change. Custom activators are still resolved from DI on every call. Because the default type is internal, user registrations can't produce it.

I added a test that registers a custom activator and checks that it's used for OnConnectedAsync, for every one of several invocations and for OnDisconnectedAsync.

Benchmarks

DefaultHubDispatcherBenchmark, BenchmarkDotNet in-process (--config perflab), 2 vCPU AMD EPYC 9V74 VM. Base and PR builds were run in interleaved order for 3 rounds; the table shows the median of those rounds.

Benchmark Before After Δ time Alloc before Alloc after
Invocation 269.2 ns 211.5 ns -21.4% 552 B 368 B
InvocationAsync 278.8 ns 220.9 ns -20.8% 552 B 368 B
InvocationReturnValue 279.6 ns 221.1 ns -20.9% 576 B 392 B
InvocationReturnAsync 299.7 ns 245.2 ns -18.2% 600 B 416 B
InvocationValueTaskAsync 306.4 ns 250.4 ns -18.3% 640 B 456 B

Per-round means for Invocation: base 269.2 / 266.4 / 273.0 ns; PR 213.9 / 211.4 / 211.5 ns.

Tests

  • Microsoft.AspNetCore.SignalR.Tests: 496 passed, 1 skipped, 0 failed. This includes the new CustomHubActivatorIsUsedForEveryInvocation test.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

…tion

Resolving the scoped IHubActivator<THub> per invocation grows the scope's
resolved-services cache and costs ~184 B and ~55 ns per call. When the
container produces the built-in DefaultHubActivator<THub>, construct it
directly with the same scoped service provider. Custom activators are
still resolved from DI on every call.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 21:50
@github-actions github-actions Bot added the area-signalr Includes: SignalR clients and servers label Oct 30, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The fast path can permanently bypass a scoped factory after it first returns the default activator, preventing later scopes from using their custom activator’s Create/Release methods.

1 open issue
What changed in this PR

This PR reduces SignalR hub-dispatch overhead by constructing the built-in hub activator directly after its first resolution, avoiding repeated scoped DI lookups.

Changes:

  • Adds cached activator selection for hub invocations and lifecycle callbacks.
  • Adds a regression test checking custom activator use across connection, invocation, and disconnection handling.
File Description
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTests.cs Tests custom activator release counts across lifecycle callbacks and repeated invocations.
src/​SignalR/​server/​Core/​src/​Internal/​DefaultHubDispatcher.cs Centralizes activator selection and adds a direct-construction fast path for the default activator.

Review effort: Balanced

Gate the DefaultHubActivator fast path on SignalR's own open generic
descriptor still being the effective registration, so factory or closed
registrations keep being resolved from DI per scope.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

Compatibility audit (no public API or behavior changes intended)

  • No PublicAPI.*.txt changes. The only additions are the internal DefaultHubActivatorRegistration type and an internal singleton registered with TryAddSingleton.
  • Custom activators: any user registration of IHubActivator<> or IHubActivator<THub>, whether by type, instance or factory, and in any order relative to AddSignalR, is still resolved from the scope on every invocation. The fast path is only taken when all of the following hold:
    • SignalR's own open-generic descriptor is the effective (last) non-keyed registration.
    • There is no closed IHubActivator<THub> registration.
    • The container actually returned DefaultHubActivator<THub>, which covers third-party containers with native registrations or decorators.
    • Tests: CustomHubActivatorIsUsedForEveryInvocation and HubActivatorFactoryIsUsedForEveryScopeEvenIfItFirstReturnsDefaultActivator.
  • Scoped services: the default activator is still created per scope, with the same scoped IServiceProvider. Hubs and their scoped dependencies resolve from exactly the same scope as before. DefaultHubActivator is internal and not disposable, so scope disposal behavior is unchanged.
  • Remaining edge case: if user code resolves IHubActivator<THub> from the invocation scope itself, it now gets a different DefaultHubActivator instance than the one the dispatcher used. The type is internal and an activator must not be reused, so this shouldn't be observable in practice. Happy to drop the caching if reviewers consider it a concern.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Source-only review of frozen head 1dccf07c97ff5ea8673617756f4f9792be5178f1 found one new P2 issue: an external container's varying scoped IHubActivator<THub> registration can be bypassed after its first scope returns the built-in activator.

The routed docs/CrossCuttingGuidance.md review completed with no unresolved candidates or required-input failures. Existing feedback #discussion_r4428822932 correctly covered the in-collection scoped-factory variant and its fix; this comment covers the remaining out-of-collection container path. Security assessment and target-code/test/CI/browser execution were excluded by the prepared guidance. No SignalR-specific guide was routed, so that domain remains uncovered beyond the cross-cutting review.

Provenance: immutable version-2 bundle for dotnet/aspnetcore#70141, merge base/base tip 4f556f73a610b386e5ec29355a300e493d30c4c5, trusted guidance commit 4f556f73a610b386e5ec29355a300e493d30c4c5. Proof is source-only; bundled tracked Git bytes cannot establish symlink, submodule, LFS target, runtime, or external-container implementation behavior.

Generated by ASP.NET Core Pull Request Review for #70141 · copilot · gpt56 · 143.4 AIC · ⌖ 11.5 AIC · ⊞ 20.2K
Comment /review to run again

…ncyInjection scopes

Other containers can supply IHubActivator<THub> outside the IServiceCollection
or vary it per scope, so keep resolving it per invocation for them.

Co-authored-by: Copilot <[email protected]>
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 13, 2026

davidfowl commented Nov 17, 2026 •

Copy link
Copy Markdown
Member Author

Merge assessment

Verdict: Hold; a SignalR reviewer requested changes, favoring a simpler first-resolved activator type check over retaining the IServiceCollection and detecting MS.DI by assembly name, but leaning toward closing the PR because even the simpler approach may not justify the ~50 ns gain. Resolve that product decision before considering a merge.

Size M: +98/−5 production lines, +176 test, +0 benchmark (uses existing DefaultHubDispatcherBenchmark); 4 files, 1 production assembly (SignalR.Core)
Impact Medium: −18% to −21% time and −184 B per hub invocation (e.g. Invocation 269 → 212 ns, 552 → 368 B), 3 rounds; SignalR only, measured on a base that predates #69557 which also changed DefaultHubDispatcher
Risk High: SignalR hub dispatch (Medium tier) raised one level because _hubActivatorKind is cached for the dispatcher's lifetime
Tests 3 new tests cover the slow path (custom open-generic activator, scoped factory that first returns the default, activator supplied outside the collection); none asserts that the default fast path is actually taken; they pin behavior and would be expected to pass on main
Review halter73 requested changes Nov 24 on 703fba6; earlier Copilot, gfoidl and automated review threads are resolved, but the latest formal review is not addressed
CI aspnetcore-ci succeeded on 703fba6 (Nov 1); no conflicts, but the run predates current main
Complexity Adds DefaultHubActivatorRegistration (scans the captured IServiceCollection), an assembly-name check for Microsoft.Extensions.DependencyInjection and a 3-state enum; reviewers must keep these in sync with DI registration rules
Reversibility Easy: 3 production files in one assembly, no public API
Security sensitivity Not assessed (repo review instructions put security out of scope)
Encoding/escaping parity n/a
Behavior / public API change None found; after the first scope, IHubActivator<THub> is no longer resolved from DI when SignalR's own descriptor is effective, which is visible only through DI diagnostics

Reasons to merge

  • Per-invocation cost drops ~55 ns and 184 B on every hub method call, plus connect/disconnect.
  • Custom activators, factory registrations and non-MS.DI containers all stay on the existing resolve-every-time path, each with a test.
  • Earlier review threads were addressed in code; the Nov 24 changes-requested review remains outstanding.

Reasons not to merge yet

  • A singleton now captures the IServiceCollection and scans it at the first invocation rather than at container build, so correctness rests on the collection not changing after build together with the DefaultHubActivator<THub> type check.
  • halter73 questions both the retained collection and assembly-name heuristic, proposes the simpler first-resolved type check as an alternative, and still leans toward closing given the cost/benefit.
  • The PR body describes the earlier type-check design and "a test", not the registration scan and 3 tests on the head.
  • Numbers predate [SignalR] Reduce hub invocation activity overhead #69557 on main, so the current gain is unknown until re-measured.

What would change this verdict: A SignalR owner would need to choose whether any version is worth merging, address the changes-requested review, and remeasure on current main before revisiting the merge case.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@PureWeen

Copy link
Copy Markdown
Member

/review

@halter73 halter73 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this be 100x simpler if we went back to checking whether the first resolved activator is DefaultHubActivator<THub>? That type is internal and sealed. An open-generic IHubActivator<> registration always constructs its ImplementationType, so with MS.DI the check can't pass in one scope and fail in another. You'd need a per-hub closed factory deliberately built around our internal type, or a third-party container decorator that conditionally returns the inner activator. I'm fine not supporting either. I don't think they justify retaining the IServiceCollection in a singleton and detecting the DI container by assembly name.

That said, this whole thing still seems pretty hacky. Even with the simpler type check, I'd lean towards closing this, since I don't think the complexity is worth the ~50ns speedup.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-signalr Includes: SignalR clients and servers pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants