SignalR通用集线器

时间:2013-07-20 08:58:38

标签: jquery asp.net asp.net-mvc-4 asp.net-web-api signalr

我正在开发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();
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我认为您不需要通用Hub,您需要的是通用参数,或者更具体的是继承锁定功能的参数

所以你需要的是:

  • 使用lock \ unlock methods
  • 使您的实体继承ILockable接口
  • 创建返回ILockable对象的Find \ Save方法的版本
  • 对返回的对象执行锁定功能,然后将其保存