skip to content

In ASP.NET Core SignalR, how long does a hub instance live, and why must you not keep state in hub fields or fire-and-forget sends?

level: middleimportance: must knowfreq 58%

answer

  1. transient, not per connection
  2. new DI scope per invocation
  3. IHubActivator creates, then Release disposes
  4. ObjectDisposedException after the method returns
  5. Context.Items or a singleton for state

basics

~20 s

A SignalR hub instance lives for one invocation: SignalR creates it in a fresh DI scope for each hub method call, OnConnectedAsync or OnDisconnectedAsync, then disposes it. Fields reset every call, and a send started after the method returns hits a disposed hub.

solid answer

~40 s

Hubs are transient. For every hub method invocation, and for `OnConnectedAsync` and `OnDisconnectedAsync`, SignalR opens a new async DI scope, asks the scoped `IHubActivator<THub>` for an instance, sets `Clients`, `Context` and `Groups`, runs the method and releases the hub, disposing it when the activator created it. So a field set in `StartQuiz` is gone in `SubmitAnswer`, scoped services behave like transients, and touching `Clients` after the method has returned throws `ObjectDisposedException`. Per-connection data goes in `Context.Items`, which lives as long as the connection; shared data goes in a thread-safe singleton service or an external store. Work that outlives the call, such as a timer that closes the question after 30 seconds, uses an injected `IHubContext<QuizHub>` instead of the hub's own `Clients`. And every `SendAsync` inside the method is awaited.

code

csharp · 16 lines
csharp
public class QuizHub(QuizState state) : Hub   // QuizState registered as a singleton
{
    public async Task JoinAs(string nickname)
    {
        // Per-connection: survives later invocations of this connection.
        Context.Items["nickname"] = nickname;
        await Clients.Caller.SendAsync("Joined", state.CurrentQuestionId);
    }

    public async Task SubmitAnswer(int questionId, int choice)
    {
        var nickname = (string?)Context.Items["nickname"] ?? "anonymous";
        state.Record(questionId, nickname, choice);   // thread-safe singleton
        await Clients.Caller.SendAsync("AnswerReceived", questionId);
    }
}

go deeper

for a junior

Remember that a hub object is created for each call and thrown away, so fields never remember anything between calls.

for a middle

Walk through the per-invocation DI scope and IHubActivator, what scoped services become inside a hub, and where Context.Items and singletons fit.

for a senior

Spot the fire-and-forget and timer bugs that end in ObjectDisposedException, and move delayed pushes to IHubContext or a hosted service.

for a principal

Decide where quiz state lives as the app grows: per-process singletons are cheap but vanish on restart and do not span servers, so plan the store early.

## One instance per call, not per connection A common first guess is that SignalR keeps one hub object per connected browser, the way a socket handler might. It does not. ASP.NET Core SignalR treats a hub as **transient**: the dispatcher creates a hub for each unit of work and throws it away afterwards. The units of work are: - each hub method a client invokes; - `OnConnectedAsync` when a connection is established; - `OnDisconnectedAsync` when it ends; - a streaming method, whose hub and scope stay alive until the stream completes. For each of those, the dispatcher opens a new **async DI scope**, resolves `IHubActivator<THub>` from it (registered as scoped), calls `Create()`, assigns `Clients`, `Context` and `Groups`, runs your code, and calls `Release(hub)` in a `finally`. When the hub class is not registered in DI, which is the normal case, the activator builds it with `ActivatorUtilities` and `Release` disposes it. ## What that means for state Because the instance is new every time, fields carry nothing between calls: ```csharp public class QuizHub : Hub { private int _currentQuestion; // reset on every invocation public void Next() => _currentQuestion++; // always ends at 1 } ``` The right homes for state, by scope: | State | Lives in | Notes | |---|---|---| | per connection, this server | `Context.Items` | an `IDictionary<object, object?>` that persists across invocations of the same connection | | shared by all connections on this server | a singleton service injected into the hub | must be thread-safe: hub invocations from different clients run concurrently | | shared across servers or restarts | a database or cache | an in-memory singleton is per process | `MaximumParallelInvocationsPerClient` defaults to 1, so one client's calls run one at a time, but calls from different clients do not wait for one another. ## Dependency injection inside a hub Constructor injection works as usual, with one twist: because the scope is per invocation, a **scoped** service such as a `DbContext` is created and disposed for each call, so scoped and transient services end up with the same lifetime inside a hub. Hub method parameters can also be services: by default SignalR resolves a parameter from DI when the container knows its type, and `[FromServices]` makes it explicit. Setting `HubOptions.DisableImplicitFromServicesParameters = true` stops the inference so only marked parameters come from DI. ## Fire-and-forget is a bug Two patterns break: 1. Calling `Clients.All.SendAsync(...)` without `await`. The docs list this as not supported: the hub method can complete, and the hub be released, before the send finishes. 2. Starting a `Task.Run` or timer that uses the hub's `Clients` later, for example to close the question after 30 seconds. `Hub.Clients`, `Hub.Context` and `Hub.Groups` check whether the hub is disposed, so that later access throws `ObjectDisposedException`. The fix for the second is to inject `IHubContext<QuizHub>`, which is a singleton not tied to any invocation, and use it from the background work: ```csharp public class QuizHub(IHubContext<QuizHub> hubContext) : Hub { public async Task OpenQuestion(int id) { await Clients.Others.SendAsync("ShowQuestion", id); _ = CloseLaterAsync(id); // uses hubContext, not this.Clients } private async Task CloseLaterAsync(int id) { await Task.Delay(TimeSpan.FromSeconds(30)); await hubContext.Clients.All.SendAsync("CloseQuestion", id); } } ``` For anything longer-lived than a single timer, the work belongs in a hosted service that holds the hub context. ## Cross-cutting code Since there is no long-lived hub object to hang logging, validation or exception handling on, SignalR provides **hub filters**: an `IHubFilter` wraps every hub method invocation (`InvokeMethodAsync`) and, optionally, `OnConnectedAsync` and `OnDisconnectedAsync`. Filters are added with `options.AddFilter<T>()` in `AddSignalR(...)` for all hubs, or in `AddHubOptions<THub>(...)` for one hub; global filters run first.

  • Where do you put logging or exception handling that must run around every hub method?
    In an `IHubFilter`. Its `InvokeMethodAsync(HubInvocationContext, next)` wraps each invocation, and it can also wrap `OnConnectedAsync` and `OnDisconnectedAsync`. Register it with `options.AddFilter<T>()` in `AddSignalR` for every hub, or in `AddHubOptions<THub>` for one; global filters run before per-hub ones, in the order added. To reject a call, throw a `HubException` instead of calling `next`.
  • If you inject a scoped DbContext into a hub constructor, how long does that context live?
    One invocation. SignalR creates a new DI scope for each hub method call, so the context is created for that call and disposed when the scope ends, or when a streaming method's stream completes. That is fine for short writes, but the hub must not run concurrent operations on that one context; `IDbContextFactory<T>` isolates each unit of work.

A hub is like a supply teacher booked for a single lesson: each lesson gets whoever is sent, notes left on the desk are cleared afterwards, and anything that must carry over goes in the school office (a singleton or Context.Items), not in the teacher's pocket.

  • Each browser connection gets one hub instance that lives until it disconnects.
  • A private field on the hub is a safe place to keep the current question.
  • Scoped services in a hub live for the whole SignalR connection.
  • Calling Clients.All.SendAsync without await is fine because SignalR queues it anyway.
  • Resolve the hub class from DI in a controller to send messages from outside it.