85

I am using SignalR to broadcast messages to all my clients. I need to trigger the broadcasting outside of my hub class i.e. something like below:

var broadcast = new chatHub(); broadcast.Send("Admin","stop the chat");

I am getting error message as:

Using a Hub instance not created by the HubPipeline is unsupported.

Jim Aho
  • 9,932
  • 15
  • 56
  • 87
Nitin Agrawal
  • 1,341
  • 1
  • 10
  • 19

2 Answers2

147

You need to use GetHubContext:

var context = GlobalHost.ConnectionManager.GetHubContext<chatHub>();
context.Clients.All.Send("Admin", "stop the chat");

This is described in more detail at http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server#callfromoutsidehub.

halter73
  • 15,059
  • 3
  • 49
  • 60
  • 4
    "context.Clients.All.Send" does not broadcast back to the caller, only to the others. any ideas? – user384080 Dec 28 '13 at 05:21
  • 5
    If you are using `GetHubContext` there is no caller as this is meant to be used outside of a Hub. `Clients.All` should address every client that is currently connected to the Hub. – halter73 Dec 30 '13 at 22:32
  • 2
    Are you sure this works for self-hosted SignalR instances as well? – Umar Farooq Khawaja Mar 10 '15 at 13:40
  • 5
    I have the same code, but the method Send or any other method would not be called . – nAviD May 30 '15 at 14:10
  • 5
    This does not get you an instance of the hub, it gives you an instance of `IHubContext`. You can't use this to call hub methods. – George Mauer Sep 12 '16 at 21:55
  • 4
    This worked for me with ONE change: `context.Clients.All.broadcastMessage("Admin", "stop the chat");` Use broadcastMessage instead of Send. – Wheel Builder Feb 16 '17 at 21:59
9

A small update for those who might be wondering where the GlobalHost has gone. SignalR has been completely rewritten for .net core. So if you are using the SignalR.Core package (Difference between SignalR versions), you get an instance of SignalR hub context by injecting it into your service:

public class MyNeedyService
{
    private readonly IHubContext<MyHub> ctx;

    public MyNeedyService(IHubContext<MyHub> ctx)
    {
        this.ctx = ctx;
    }

    public async Task MyMethod()
    {
        await this.ctx.All.SendAsync("clientCall");
    }
}

And in Startup.cs:

services.AddSignalR()/*.AddAzureSignalR("...")*/;

Microsoft docu is here: Send SignalR messages from outside the hub.

Maxim Zabolotskikh
  • 3,091
  • 20
  • 21