Casey Daly
Casey Daly

Reputation: 433

Instantiate SignalR Hub Object With IHubContext

It seems like a big use for SignalR Hubs is to display the actions of one client to all of the other clients. What I hope to use SignalR for is when a certain event happens in my server side code, I want to instantiate a hub object and invoke one of its methods to communicate with all of the clients. If you see my previous post (Route To Take With SqlDependency OnChange), I would like to do this in the OnChange method of SqlDependency. Upon researching it I have found some people talk about using an IHubContext object, though I haven't found many examples of instantiation and actual sending data to clients.

Is this possible to do (and what might sending data to all clients with IHubContext look like if possible), and if not, are there any ways I might be able to get around instantiating a hub like this?

Upvotes: 7

Views: 10672

Answers (2)

anbuj
anbuj

Reputation: 519

You need to use using Microsoft.AspNet.SignalR library.

using Microsoft.AspNet.SignalR;

//Instantiating. SignalRHub is the hub name.
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();

//sends message
context.Clients.Client(ClientId).sendMessage(data);

Upvotes: 1

Alex Wiese
Alex Wiese

Reputation: 8370

SignalR for ASP.NET Core

You can create a class that has the IHubContext<T> injected in. Inject other dependencies if you want, or resolve the service from controllers or other classes.

public class NotificationService
{
    private readonly IHubContext<MyHub> _myHubContext;

    public NotificationService(IHubContext<MyHub> myHubContext)
    {
        _myHubContext= myHubContext;
    }

    public async Task SendMessage(string message)
    {
        await _myHubContext.Clients.All.SendAsync("Update", message);
    }      
}

Assuming you're using SqlDependency from an IHostedService:

public class MyHostedService : IHostedService
{
     public MyHostedService(
          NotificationService notificationService)
     {
          // TODO get reference to sqlDependency
          sqlDependency.OnChange += (s, e) => _notificationService.SendMessage(e.Info.ToString());
     }         
}

SignalR for ASP.NET

var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.sendMessage(message);

Upvotes: 7

Related Questions