Skip to content

Avoid resolving the default hub activator from DI for every hub invocation - #70144

Closed
davidfowl wants to merge 3 commits into
mainfrom
perf/signalr-default-hub-activator
Closed

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

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Avoid resolving the default hub activator from DI for every hub invocation

  • Read the Contributor Guide and Code of Conduct.
  • Include unit tests for the changed behavior.
  • Include inline documentation where applicable.
  • Link an existing issue. No issue is linked to this PR.

Cut the per-invocation DI cost of creating hubs with the default activator.

Description

IHubActivator<> is registered as scoped (TryAddScoped(typeof(IHubActivator<>), typeof(DefaultHubActivator<>))). DefaultHubDispatcher creates a new scope for every hub invocation (and for OnConnectedAsync, OnDisconnectedAsync and OnAuthenticationRefreshedAsync) and resolves the activator from it. That scoped resolution is often the only thing that populates the scope's resolved-services dictionary, so each invocation also paid for the dictionary's buckets and entries, plus the DI lookup.

The dispatcher now resolves the activator through DI the first time, as before. It switches to constructing new DefaultHubActivator<THub>(scope.ServiceProvider) directly, which is the same object DI would create, only when two things hold:

  • the resolved instance is the internal DefaultHubActivator<THub>, and
  • the registration snapshot shows it's the unchanged default. AddSignalRCore registers an internal HubActivatorRegistrations singleton that's built after the container and reads the non-keyed IHubActivator<> descriptors: the last open-generic one must be DefaultHubActivator<>, and there must be no closed IHubActivator<THub> registration.

Custom activators, factories (including ones that sometimes return the default), decorators and per-hub overrides keep being resolved from DI on every call.

Hub creation and release are unchanged. DefaultHubActivator still resolves THub from the scoped provider when it's registered, or creates it with ActivatorUtilities and disposes it on release. No public API changes.

When hub constructors resolve other scoped services, the scope's dictionary is allocated anyway. The saving in that case is just the DI lookup for the activator.

Benchmark

DefaultHubDispatcherBenchmark (existing), BenchmarkDotNet InProcess with MemoryDiagnoser, --warmupCount 3 --iterationCount 15. 2 vCPU Linux VM, .NET 12 (repo SDK), Release. Rounds were interleaved: base, PR, base, PR.

Benchmark Before (2 rounds) After (2 rounds) Allocated before → after
Invocation 273.1 / 269.0 ns 239.1 / 219.4 ns (-15%) 552 → 368 B (-33%)
InvocationAsync 280.1 / 308.2 ns 221.6 / 221.8 ns (-23%) 552 → 368 B
InvocationReturnValue 278.9 / 298.3 ns 225.2 / 223.8 ns (-22%) 576 → 392 B
InvocationReturnAsync 306.4 / 298.6 ns 243.1 / 248.7 ns (-19%) 600 → 416 B
InvocationValueTaskAsync 312.9 / 301.3 ns 248.2 / 244.7 ns (-20%) 640 → 456 B
StreamChannelReader 625.8 / 592.9 ns 590.8 / 598.6 ns 1,872 → 1,688 B
StreamChannelReaderAsync 671.9 / 673.9 ns 631.2 / 589.9 ns 1,968 → 1,784 B
StreamIAsyncEnumerableCompletedTaskCount_Zero 507.9 / 525.5 ns 432.9 / 475.4 ns 1,112 → 928 B

Every invocation path allocates 184 B less. The remaining stream and upload benchmarks involve thread hops, so their timings are too noisy on this VM to call either way; their allocations also drop by about 184 B. An allocation-tick breakdown of Invocation confirms that the scope's Entry[] and int[] buckets are no longer allocated.

Tests

  • Microsoft.AspNetCore.SignalR.Tests: 500 passed, 1 skipped (pre-existing). Four new tests:
    • HubConnectionHandlerTests.DefaultHubActivatorCreatesAndDisposesHubForEachInvocation: after the fast path is enabled, each invocation still gets a fresh hub that is disposed.
    • HubConnectionHandlerTests.DefaultHubActivatorDoesNotDisposeHubResolvedFromServiceProvider: a hub registered in DI is still resolved from DI and never disposed by the activator.
    • HubConnectionHandlerTests.ScopedHubActivatorFactoryIsResolvedForEveryScopeEvenIfItReturnsTheDefaultActivator: a scoped factory that returns the default activator in some scopes is still resolved for every scope.
    • HubConnectionHandlerTests.HubActivatorRegistrationsOnlyReportsTheUnchangedDefaultRegistration: keyed registrations, closed per-hub registrations and later open-generic registrations are handled.
  • The existing custom IHubActivator tests (singleton and scoped registrations) pass unchanged.

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

…ation

The default IHubActivator<THub> is registered as scoped, so every hub
invocation (and OnConnected/OnDisconnected) resolved it from a new scope,
which populates the scope's resolved-services storage. Once the resolved
activator is known to be the internal DefaultHubActivator<THub>, which can
only come from the default registration, create it directly over the
scoped service provider instead.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 22:53
@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 singleton dispatcher can permanently bypass a scoped activator factory after resolving one default instance, causing later scopes to ignore custom activator creation and release behavior.

1 open issue
What changed in this PR

This PR reduces SignalR hub activation overhead by constructing the default activator directly after detecting it, avoiding repeated scoped DI resolution.

Changes:

  • Routes hub invocations and lifecycle callbacks through a shared activator-selection helper.
  • Adds tests for hub disposal and DI-owned hub lifetime behavior.
  • Adds a disposal-count method to the existing test hub.
File Description
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTestUtils/​Hubs.cs Exposes disposal counts for test assertions.
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTests.cs Adds activation and disposal lifecycle tests.
src/​SignalR/​server/​Core/​src/​Internal/​DefaultHubDispatcher.cs Adds the default-activator fast path for invocations and lifecycle callbacks.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

Pushed an empty commit (bca790c) to retrigger CI. The only failure was the Blazor E2E test ServerRoutingTest.NavigationLock_CanBlockExternalNavigation on Linux (Mono server), which Build Analysis lists at a 25.18% failure rate. It's a browser navigation assertion unrelated to hub activator resolution.


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

Copy link
Copy Markdown
Member Author

Superseded by #70141, which contains the same change. Closing this duplicate is left to maintainers.


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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants