我已遵循本指南ASP.NET SignalR Hubs API Guide (How to manage group membership from the Hub class),但无法让我的服务器端ShipmentHub
方法执行。
我的ShipmentHub
课程如下:
public class ShipmentHub : Hub
{
IShipmentLogic shipmentLogic;
public ShipmentHub(IShipmentLogic shipmentLogic)
{
this.shipmentLogic = shipmentLogic;
}
public void CreateShipment(IEnumerable<Shipment> shipments)
{
// Clients.All.createShipment(shipments.OrderByDescending(s => s.CreatedDate));
Clients.Group(shipments.FirstOrDefault().ShipmentId)
.createShipment(shipments.OrderByDescending(s => s.CreatedDate));
}
public async Task WatchShipmentId(string shipmentId)
{
await Groups.Add(Context.ConnectionId, shipmentId);
Clients.Group(shipmentId).createShipment(shipmentLogic.Get(shipmentId, true));
}
public Task StopWatchingShipmentId(string shipmentId)
{
return Groups.Remove(Context.ConnectionId, shipmentId);
}
}
我的客户或多或少看起来像这样:
var shipmentHub = $.connection.shipmentHub;
$.connection.hub.logging = true;
$.connection.hub.start();
var shipmentId = "SHP-W-GE-100122";
if (previousShipmentId) {
shipmentHub.server.stopWatchingShipmentId(previousShipmentId);
}
if (shipmentId.length) {
previousShipmentId = shipmentId;
shipmentHub.server.watchShipmentId(shipmentId);
}
在SignalR客户端日志中,我看到正在调用这些日志:
SignalR:调用shipmenthub.WatchShipmentId
SignalR:调用shipmenthub.StopWatchingShipmentId
SignalR:调用shipmenthub.WatchShipmentId
除了日志之外,这些方法被击中:
proxies['shipmentHub'].server = {
createShipment: function (shipments) {
return proxies['shipmentHub'].invoke.apply(proxies['shipmentHub'], $.merge(["CreateShipment"], $.makeArray(arguments)));
},
stopWatchingShipmentId: function (shipmentId) {
return proxies['shipmentHub'].invoke.apply(proxies['shipmentHub'], $.merge(["StopWatchingShipmentId"], $.makeArray(arguments)));
},
watchShipmentId: function (shipmentId) {
return proxies['shipmentHub'].invoke.apply(proxies['shipmentHub'], $.merge(["WatchShipmentId"], $.makeArray(arguments)));
}
};
而且,作为最后一点,在我添加Watch
和StopWatching
方法之前,其他所有方法都有效(即CreateShipment
会毫无问题地调用Client.All.createShipment
方法)
答案 0 :(得分:0)
您需要等待与服务器的连接建立,然后才能从客户端开始调用服务器上的方法。 hub.start()返回一个promise,这是一旦解决了这个promise后做某事的基本模式。
var shipmentHub = $.connection.shipmentHub;
$.connection.hub.logging = true;
$.connection.hub.start().done(talkToServer);
var talkToServer=function(){
var shipmentId = "SHP-W-GE-100122";
if (previousShipmentId) {
shipmentHub.server.stopWatchingShipmentId(previousShipmentId);
}
if (shipmentId.length) {
previousShipmentId = shipmentId;
shipmentHub.server.watchShipmentId(shipmentId);
}
}
答案 1 :(得分:0)
问题是由ShipmentHub
中的参数化构造函数引起的。根据{{3}}:
默认情况下,SignalR期望集线器类具有无参数构造函数。但是,您可以轻松注册一个函数来创建集线器实例,并使用此功能执行DI。通过调用GlobalHost.DependencyResolver.Register。
注册该函数
因此,您需要修改Startup.Configuration(IAppBuilder app)
方法以解决依赖关系:
GlobalHost
.DependencyResolver
.Register(
typeof(ShipmentHub),
() => new ShipmentHub(new ShipmentLogic()));