Calling SignalR hub clients from elsewhere in system

后端 未结 5 995
情书的邮戳
情书的邮戳 2020-12-07 12:06

I\'ve set up a SignalR hub to communicate between the server and client. The hub server side code is stored in a class called Hooking.cs. What I want is to be able to call a

相关标签:
5条回答
  • 2020-12-07 12:43

    You can easily use a hub by following this 2 step-

    1. Instantiating by dependency injection like this-

      public class ClassName
      {
          ........
          ........
          private IHubContext _hub;
      
          public BulletinSenderController(IConnectionManager connectionManager)
          {
              _hub = connectionManager.GetHubContext<McpHub>();
              ........
              ........
          }
      
          ............
          ............
      }
      

    2.Using the hub object like this-

    _hub.Clients.All.onBulletinSent(bulletinToSend);
    

    More can be found here.

    Example code can be found in this git repo.

    0 讨论(0)
  • 2020-12-07 12:46

    This is the correct way for SignalR 2.x:

    var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    context.Clients.All.addMessage(message);
    

    Basically, you can use the dependency resolver for the current host to resolve the IConnectionManager interface which allows you to get ahold of the context object for a hub.

    Further information can be found in the official documentation.

    0 讨论(0)
  • 2020-12-07 12:46

    Hub.GetClients has disappeared in version 0.4.0.

    From the wiki you can now use:

    IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
    dynamic clients = connectionManager.GetClients<MyHub>();
    
    0 讨论(0)
  • 2020-12-07 12:48

    Have a look at how it's done in Chat.cs in SignalR.Samples.Hubs.Chat from https://github.com/SignalR/SignalR.

    I can see in there that static Dictionary<TKey, TValue>'s are being instantiated at the top, so I imagine they are being maintained persistently too, either with the Chat class being a persisted instance (?) or that array being updated somehow.

    Check it out, David Fowler would probably be the best on this.

    0 讨论(0)
  • 2020-12-07 12:54

    This has changed in .NET Core 2, now you can use dependency injection like this:

        private readonly IHubContext<MyHub,IMyHubInterface> _hubContext;
    
        public MyController(MyHub,IMyHubInterface hubContext)
        {
            _hubContext = hubContext;
        }
    
        public bool SendViaSignalR()
        {
            _hubContext.Clients.All.MyClientSideSignalRMethod(new MyModel());
            return true;
        }
    
    0 讨论(0)
提交回复
热议问题