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 ?
Hubs are SignalR's high level API that allow both realtime client-to-server and server-to-client RPC over HTTP. The hub supports 1-to-many RPC e.g.: all clients, groups of clients, just the caller etc. Transport is over one of the following (best to worst): WebSocket, server sent events, forever frame, long polling.
Or you can also add SignalR to a project by opening the "Tools" | "Library Package Manager" | "Package Manager Console" and running the command: "install-package Microsoft. AspNet. SignalR". Now again add the SignalR class.
SignalR is an asynchronous signaling library for ASP.NET that our team is working on to help build real-time multi-user web application.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With