我正在开发ASP.net Web Api,SignalR,希望将消息发送给所有用户,在实体更新时更新锁定其他用户,但希望避免在HUB和Web API Controller中复制代码。
我希望通用代码代表所有实体的以下行为,而不是每个实体1个。
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();
}
}
}
答案 0 :(得分:0)
我认为您不需要通用Hub,您需要的是通用参数,或者更具体的是继承锁定功能的参数
所以你需要的是: