Getting current hub in SignalR

2019-02-08 18:44发布

问题:

Is there a good way to call methods in SignalR hub from a controller ?

Right now I have this:

public class StatsHub : Hub
{
    private static readonly Lazy<StatsHub> instance = new Lazy<StatsHub>(() => new StatsHub());
    public static StatsHub Instance { get { return instance.Value; } }

    public StatsHub()
    {
        if (this.Clients == null)
        {
            var hubContext = SignalR.GlobalHost.ConnectionManager.GetHubContext<StatsHub>();
            this.Clients = hubContext.Clients;
            this.Groups = hubContext.Groups;
        }
    }

    // methods here...
}

so in my controller actions I can just say, for example

StatsHub.Instance.SendMessage("blah");

and it's almost good, except that hubContext doesn't have Caller or Context properties of Hub - which are nice to have.

Hopefully, there's a better way to do this ?

回答1:

If you want to broadcast over a hub from outside of the hub, you need GlobalHost.ConnectionManager.GetHubContext<MyHub>() to get ahold of the hub context. You can then use this context to broadcast via the .Clients property.

As indicated in your sample code you already get ahold of the hub context, but doing so inside the hub just doesn't feel right in my opinion. If you're only using the logic in SendMessage() from your controller actions, I'd move the code right into the controller action and use the hub context obtained via GetHubContext<T>() from there.

Please note that the Caller or Context property will always be null in this scenario, because SignalR wasn't involved when making a request to the server and therefore cannot provide the properties.



回答2:

Found a DefaultHubManager, which is what I need, I think.

DefaultHubManager hd = new DefaultHubManager(GlobalHost.DependencyResolver);
var hub = hd.ResolveHub("AdminHub") as AdminHub;
hub.SendMessage("woohoo");

Works. If there's an even better/preferred way - please share.



标签: signalr