Jquery 信号通用集线器
我正在使用ASP.net Web Api,Signal,希望向所有用户发送消息,在实体更新时锁定其他用户,但希望避免在HUB和Web Api控制器中重复代码 我希望通用代码代表所有实体的以下行为,而不是每个实体1Jquery 信号通用集线器,jquery,asp.net,asp.net-mvc-4,asp.net-web-api,signalr,Jquery,Asp.net,Asp.net Mvc 4,Asp.net Web Api,Signalr,我正在使用ASP.net Web Api,Signal,希望向所有用户发送消息,在实体更新时锁定其他用户,但希望避免在HUB和Web Api控制器中重复代码 我希望通用代码代表所有实体的以下行为,而不是每个实体1 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.Sig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalRGridDemo.Models;
using System.Data;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace SignalRGridDemo.Hubs {
[HubName("employee")]
public class EmployeeHub : Hub {
private static ConcurrentDictionary<string, List<int>> _mapping = new ConcurrentDictionary<string, List<int>>();
private SignalRGridDemoContext db = new SignalRGridDemoContext();
public override Task OnConnected() {
_mapping.TryAdd(Context.ConnectionId, new List<int>());
Clients.All.newConnection(Context.ConnectionId);
return base.OnConnected();
}
public void Lock(int id) {
var employeeToPatch = db.Employees.Find(id);
employeeToPatch.Locked = true;
db.Entry(employeeToPatch).State = EntityState.Modified;
db.SaveChanges();
Clients.Others.lockEmployee(id);
_mapping[Context.ConnectionId].Add(id);
}
public void Unlock(int id) {
UnlockHelper(id);
_mapping[Context.ConnectionId].Remove(id);
}
private void UnlockHelper(int id) {
var employeeToPatch = db.Employees.Find(id);
employeeToPatch.Locked = false;
db.Entry(employeeToPatch).State = EntityState.Modified;
db.SaveChanges();
Clients.Others.unlockEmployee(id);
}
public override Task OnDisconnected() {
foreach (var id in _mapping[Context.ConnectionId]) {
UnlockHelper(id);
}
var list = new List<int>();
_mapping.TryRemove(Context.ConnectionId, out list);
return base.OnDisconnected();
}
}
}
我不认为您需要一个通用集线器,您需要的是一个通用参数,或者更具体地说,是一个继承锁功能的参数 因此,您需要的是: 使用lock\unlock方法使实体继承一个ILockable接口 创建一个返回ILockable对象的Find\Save方法的版本 对返回的对象执行锁定功能,然后保存它