I am using Microsoft.AspNetCore.SignalR
(latest release) and would like to get the hub context from within another object that's not a Controller
. In the "full" SignalR, I could use GlobalHost.ConnectionManager.GetHubContext<MyCoolHub>();
I have seen a lot of examples of just adding Microsoft.AspNetCore.SignalR.IHubContext<MyCoolHub>
as a parameter to the Ctor of a Controller
, but no examples (that work) for otherwise.
ETA:
So, this is what I have working. Is this hacky?
public class MyHub : Hub
public static IHubContext<MyHub> GlobalContext { get; private set; }
public MyHub(IHubContext<MyHub> ctx){
GlobalContext = ctx;
}
}
Then I can call it as so:
await MyHub.GlobalContext.Clients.All.InvokeAsync(...)
So after looking over this example from the accepted answer, I didn't quite get where he was going, so I tried a few things and I think I got what he was saying. So, for folks who have this issue in the future, I want to change that example to a fully working example.
So we are going to create a "Shared Methods", like in the example:
Then, in your
Hub
object, you add a constructor, like so:In your
Startup.cs
, you inject the shared class like so:This still works as it normally would:
Just set
IHubContext<MyHub> hubContext
on calling-side constructor.I would recommend using .net core default DI container mechanism, not creating static property.
Please refer to How do I get a reference to a Hub?