1

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?

Yahia
  • 805
  • 7
  • 25
  • 1
    Have you tried to inject a strongly-typed HubContext? As it is said in this article: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-2.2 (see section "Inject a strongly-typed HubContext") – Jorge Cavaleiro Dias Dec 09 '18 at 18:45
  • It seems a strongly-typed hubcontext has no other added value than to call specific methods in the client js side on the js command connection.on("method_to_call"). For my need, I ended up defining `GetAllActiveConnections` as static in the hub, and using it from the hubcontext (see [How to iterate over users in asp.net core SignalR?](https://stackoverflow.com/a/51382662) – Yahia Dec 14 '18 at 09:02

1 Answers1

0

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);
}
Yahia
  • 805
  • 7
  • 25