Passing strongly typed hubs to SignalR

I just updated some SignalR links and things have changed a bit to allow typed Hub<T> hubs. In existing examples and documentation, such as:

Server-Broadcast-with-Signalr

we have a static class containing references to clients through the following mechanisms:

 public class StockTicker() { private readonly static Lazy<StockTicker> _instance = new Lazy<StockTicker>( () => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients)); IHubConnectionContext Clients {get;set;} private StockTicker(IHubConnectionContext clients) { Clients = clients; } } 

So, the static link is checked, and if null is:

 GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients 

to instantiate and provide clients through the constructor.

So that was how it worked, and indeed, how it has a url in it. But now with Hub<T> in the constructor a small change is required:

  private StockTicker(IHubConnectionContext<dynamic> clients) { Clients = clients; } 

Now my question is how can I extend this further so that my version of StockTicker can have a strongly typed property for clients like x.

  IHubConnectionContext<StockTickerHub> Clients {get;set;} private StockTicker(IHubConnectionContext<dynamic> clients) { Clients = clients; // Fails, wont compile } 

By supporting strongly typed links, I could call strongly typed methods, etc.

+8
c # signalr signalr-hub
source share
3 answers

Now there is a new GetHubContext overload, which takes two common parameters. The first is the Hub type, as before, but the second common parameter is TClient (which is T in the Hub<T> ).

Assuming StockTickerHub is defined as follows:

 public class TypedDemoHub : Hub<IClient> 

Then

 GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients 

becomes

 GlobalHost.ConnectionManager.GetHubContext<StockTickerHub, IClient>().Clients 

The type returned by the new overload in GetHubContext will be IHubContext<IClient> , and the Clients property will be IHubConnectionContext<IClient> instead of IHubConnectionContext<dynamic> or IHubConnectionContext<StockTickerHub> .

+23
source share

Or look:

https://github.com/Gandalis/SignalR.Client.TypedHubProxy

It contains more features than the TypeSafeClient mentioned above.

+2
source share

Take a look at:

https://github.com/ieb/SignalR-TypeSafeClient

May be helpful!

0
source share

All Articles