0
我正在研究ASP.net Web Api,SignalR,希望將消息發送給所有用戶,在更新實體時更新鎖定其他用戶,但希望避免重複HUB和Web API控制器中的代碼。SignalR Generic Hub
我希望泛型代碼表示下面的行爲,而不是每個實體都有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();
}
}
}