Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Casey Daly Avatar asked Jul 10 '18 23:07

Casey Daly


1 Answers

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);
like image 170
Alex Wiese Avatar answered Oct 13 '22 18:10

Alex Wiese