I am using a hubcontext passed via DI in my ASP.Net Core application using a hub helper as described in this post "How can I pass a SignalR hub context to a Hangfire job on ASP .NET Core 2.1?". Basically, I am using a helper that maintains a SignalR hubContext to send messages outside from the hub from the server to connected clients.
Now, I am also trying to keep a list of my connected clients by overriding onConnected
method of my SignalR hub as described in this post "How to iterate over users in asp.net core SignalR?", in order to be able to send individual (i.e. specialized) messages.
The problem is that the suggested solution works from the inside of the hub, while when passing the hubContext via DI, I have only access to the hub from the outside.
So for example in my hub helper, I can access _hubContext.Clients
but not to _hubContext.Context
for example or any of the public methods like onConnected
.
Any suggestion?
For my need, I ended up defining GetAllActiveConnections as static in the hub, and using it from the hub helper in conjunction with the injected hubcontext.
My hub contains a static field:
static HashSet<string> CurrentConnections = new HashSet<string>();
and a static public method that uses this field:
public Task GetAllActiveConnections() { ... }
Then my hub helper uses the static method from the hub.
foreach (var activeConnection in MyHub.GetAllActiveConnections())
{
hubcontext.Clients.Client(activeConnection).SendAsync("hi conn : " + activeConnection);
}