在SignalR传递强类型集线器 [英] Passing strongly typed Hubs in SignalR
问题描述
我刚刚更新了一些SignalR引用和事情,以允许一般类型的集线器集线器和LT有所改变; T>
。在现有的实例和文档,如在:
I've just updated some SignalR references and things have changed somewhat in order to allow for generically typed Hubs Hub<T>
. In the existing examples and documentation such as at:
<一个href=\"http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-server-broadcast-with-signalr-20\">Server-Broadcast-with-Signalr
我们有一个静态类通过以下机制保持对客户的引用:
we have a static class holding references to clients via 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;
}
}
因此,一个静态引用检查,如果为null,伸出手来:
So a static reference is checked and if null it reaches out to :
GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients
要创建一个实例,通过构造提供的客户端。
to create an instance and supply the clients via the constructor.
的因此,这是它如何用来工作的确实是上面的网址怎么有它。但现在集线器&LT; T&GT;
有一个在构造函数中所需略有变化:
So this was how it used to work and indeed is how the url above has it. But now with Hub<T>
there is a slight change required in the constructor:
private StockTicker(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
现在我的问题是如何延长这进一步使得我StockTicker版本可以对X型的客户一个强类型属性。
Now my question is how can I extend this further such that my version of StockTicker can have a strongly typed property for clients of type x.
IHubConnectionContext<StockTickerHub> Clients {get;set;}
private StockTicker(IHubConnectionContext<dynamic> clients)
{
Clients = clients; // Fails, wont compile
}
通过保持强类型的引用,我将能够调用强类型的方法等。
By maintaining strongly typed references I would be able to call strongly typed methods, etc.
推荐答案
现在有GetHubContext的新重载需要两个泛型参数。首先是枢纽型像以前一样,但第二个泛型参数是TClient。(这是T在集线器&LT; T&GT;
)
There is now a new overload of GetHubContext that takes two generic parameters. The first is the Hub type like before, but the second generic parameter is TClient (which is the T in Hub<T>
).
假设StockTickerHub定义如下:
Assuming that StockTickerHub is defined as follows:
public class TypedDemoHub : Hub<IClient>
然后
GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients
变为
GlobalHost.ConnectionManager.GetHubContext<StockTickerHub, IClient>().Clients
由新的过载GetHubContext返回的类型将是 IHubContext&LT; IClient&GT;
和客户属性将被 IHubConnectionContext&LT; IClient&GT;
,而不是 IHubConnectionContext&LT;动态&GT;
或 IHubConnectionContext&LT; StockTickerHub方式&gt;
The type returned by the new overload to GetHubContext would be IHubContext<IClient>
and the Clients property would be IHubConnectionContext<IClient>
instead of IHubConnectionContext<dynamic>
or IHubConnectionContext<StockTickerHub>
.
这篇关于在SignalR传递强类型集线器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!