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 ?
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 viaGetHubContext<T>()
from there.Please note that the
Caller
orContext
property will always benull
in this scenario, because SignalR wasn't involved when making a request to the server and therefore cannot provide the properties.Found a DefaultHubManager, which is what I need, I think.
Works. If there's an even better/preferred way - please share.