Search code examples
asp.net-core-mvcsignalr-hubasp.net-core-signalr

How do I associate data with a SignalR connection in .NET Core?


In my old SignalR (pre-Core) project, I used to have a static ConcurrentDictionary<string, MyConnectionClass> Connections = new ...; to represent my individual connections with additional data acquired during the connection life time.

How do I solve this in SignalR for .NET Core?

I am looking at this manual: https://medium.com/@andrejsabrickis/recap-creating-a-demo-of-real-time-communication-app-using-aspnetcore-signalr-d8ac0afba081

which uses the following:

private readonly ConcurrentDictionary<HubConnectionContext, UserDetails> _usersOnline;

Now, I'm wondering if I should use the HubConnectionContext as a key. Is it safe to use? Will that instance always be associated with the connection id for as long as the connection is viable? I'm not using load balancing of any kind.


Solution

  • Now, I'm wondering if I should use the HubConnectionContext as a key. Is it safe to use? Will that instance always be associated with the connection id for as long as the connection is viable?

    No. The implementation described by that article actually uses:

    1. ConcurrentDictionary<string, UserDetailsDto>

    2. _userTracker.AddUser(connection.ConnectionId, new UserDetailsDto (...))

    connection.ConnectionId is safe to use and sufficient to associate data with the connection.