Search code examples
signalrsignalr-hubasp.net-core

How to get SignalR Hub Context in a ASP.NET Core?


I'm trying to get the context for a hub using the following:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<SomeHub>();

The problem is that GlobalHost is not defined. I see it is part of the SignalR.Core dll. At the moment, I have the following in my project .json file, under dependencies:

"Microsoft.AspNet.SignalR.Server": "3.0.0-*"

If I add the latest available version of Core:

"Microsoft.AspNet.SignalR.Server": "3.0.0-*",
"Microsoft.AspNet.SignalR.Core" :  "2.1.2"

I get a whole bunch of errors because server and core are conflicting. If I change them to both use version "3.0.0-*", all the conflicts go away, but GlobalHost cannot be found. If I remove Server, and just user Core version 2.1.2 then GlobalHost works, but all the other things needing Server, obviously do not.

Any ideas?


Solution

  • Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager is a DI injected service through which you can get the hub context...For example:

    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Infrastructure;
    using Microsoft.AspNet.Mvc;
    
    public class TestController : Controller
    {
         private IHubContext testHub;
    
         public TestController(IConnectionManager connectionManager)
         {
             testHub = connectionManager.GetHubContext<TestHub>();
         }
     .....