Search code examples
asp.net-coresignalrsignalr-hubasp.net-core-signalr

Optimal way to retrieve hub context in SignalR 3.0 from anywhere


I am working on a Asp .NET 3.1 application using SignalR 3.0 and I need the ability to access the hubcontext at any time. I regularly and receiving data and processing it to push out to the clients when a timer event fires. This means I can rely on the ability to access the hubcontext when the client calls a hub method or through the controllers or middleware. Since I cannot use GlobalHost in this version of signalR, what is the optimum way to do this?

I have tried several different things, I originally thought to keep a static reference to the hubcontext but I don't think that is a very reliable method. I thought to keep a static reference to an IServiceProvider, but by the time my timers fired, the service provider had been disposed. Any suggestions?


Solution

  • If you are using standard Asp.Net Core Dependency Injection (IServiceCollection) you can inject IHubContext<ChatHub> in constructor of your service:

        public class NotificationsHub : Hub
        {
        }
    
        public class NotificationService(IHubContext<NotificationsHub> notificationsHub) : INotificationService
        {
        }
    
        // ***** At Startup ********
    
        // SignalR registration
        private static void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
          app.UseSignalR(routes =>
          {
            routes.MapHub<NotificationsHub>(hubRoute);
          });
        }
    
        // dependencies registration
        public static IServiceCollection RegisterServices(IServiceCollection services)
        {
          services.AddSingleton<INotificationsService, NotificationService>();
        }
    

    Does it work for you ?