【问题标题】:Client connected event outside of SignalR hubSignalR 集线器外部的客户端连接事件
【发布时间】:2016-05-03 18:55:04
【问题描述】:

我正在寻找一种简单的方法来通知 SignalR 集线器外部的代码关于新的客户端连接。

我该怎么做?

【问题讨论】:

    标签: asp.net-mvc signalr


    【解决方案1】:

    您需要在您的中心类中使用Dependency Injection
    一个易于与 SignalR 集成的IoC ContainerAutofac

    public class NotifyHub : Hub
    {
        private readonly ILifetimeScope _hubLifetimeScope;
        private readonly IHubService _hubService;
    
        public NotifyHub(ILifetimeScope lifetimeScope)
        {
            // Create a lifetime scope for the hub.
            _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
    
            // Resolve dependencies from the hub lifetime scope.
            _hubService = _hubLifetimeScope.Resolve<IHubService>();
        }
    
        public override Task OnConnected()
        {
            string name = Context.User.Identity.Name;
            //Or whatever you want to send
            _hubService.CustomNotify(name, Context.ConnectionId);
            return base.OnConnected();
        }
    
        protected override void Dispose(bool disposing)
        {
            // Dipose the hub lifetime scope when the hub is disposed.
            if (disposing && _hubLifetimeScope != null)
            {
                _hubLifetimeScope.Dispose();
            }
            base.Dispose(disposing);
        }
    }
    

    另外,你需要provide dependency injection integration for SignalR hubs:

    var builder = new ContainerBuilder();
    //other IoC registrations
    builder.RegisterType(typeof(HubService)).As(typeof(IHubService)).InstancePerRequest();
    builder.RegisterType<GaugeHub>().ExternallyOwned();
    
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多