Nadav Hury
Nadav Hury

Reputation: 679

Responding to events in a SignalR hub

I'm looking for a way to first expose an event in my repository class, and register to that event in my signalr hub, for example if a user was added to my application all the connected users will get notified. I'm using asp.net Mvc in my backend. What is the recommended approach for doing so, where should I start?

Upvotes: 0

Views: 345

Answers (1)

N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

If you want to notify other clients it's as simple as executing a message on all connected clients.

AKA:

class MyHub : Hub 
{
    public void AddUserToApplication()
    {
        ...Your logic to add your user...
        Clients.All.newUserInApp(); // newUserInApp would then have to be defined on the client.
    }
}

If you then want to perform this type of behavior outside of your hub, aka maybe in a timer you can access the hubs "Clients" property via:

IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

So you can then do:

context.Clients.All.newUserInApp();

Upvotes: 3

Related Questions