3

I'm looking for a way to call a method, from another class in my project, that will then send a message to all clients connected to the mainHub

I have a static method where I'm trying to send data to all clients connected to the mainHub which is a SignalR Core hub. I am able to get the hub's context however, since this method is static, that hub's context requires an object reference.

In regular SignalR, I was able to use

var context = GlobalHost.ConnectionManager.GetHubContext<mainHub>();

I could then call this context.Clients.All. However, this does not exist in SignalR Core.

public class utils : Controller
{
    private readonly IHubContext<mainHub> _hubContext;

    public utils(IHubContext<mainHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public static void addManagementLog(sstructs.ManageLog mngLog)
    {
        _hubContext.Clients.All.SendAsync("newManageLog", mngLog);
    }
}

An object reference is required for the non-static field, method or property utils._hubContext

What's the best way to use this hub context in a static method, or in a way that I can call this addManagementLog() method from other classes in this project?

Brian S
  • 385
  • 3
  • 16
  • 1
    This might answer the question; https://stackoverflow.com/questions/27299289/how-to-get-signalr-hub-context-in-a-asp-net-core or this: https://stackoverflow.com/questions/37318209/asp-net-core-rc2-signalr-hub-context-outside-request-thread/38832879#38832879 – Nisarg Shah Jul 29 '19 at 05:53
  • @Nisarg I am already using the solution provided in this question, by using the new IHubContext<> However, the issue is with calling this in a static method. – Brian S Jul 29 '19 at 05:58
  • 1
    Can you set that to a static variable when you get it in the constructor? – Nisarg Shah Jul 29 '19 at 06:04
  • Right, that's what seems to be the issue. I've been trying different variants of: ```IHubContext cntxt = new IHubContext; cntxt.Clients.All.SendAsync("newManageLog", mngLog); ``` There's either something wrong with my syntax, or I can't create a static variable of a IHubContext. "Cannot create an instance of the abstract class or interface IHubContext" – Brian S Jul 29 '19 at 06:09

0 Answers0