Lee Grainger
Lee Grainger

Reputation: 206

How do you get a reference to an ASP.NET Core SignalR hub context outside of a controller?

I have just started using SignalR for ASP.NET Core. I have used SignalR for ASP.NET for a couple of years.

I am using:

Microsoft.AspNetCore.All 2.0.7
Microsoft.AspNetCore.SignalR 1.0.0-preview2-final
Microsoft.AspNetCore.SignalR.Client 1.0.0-preview2-final

It appears that in the ASP.NET Core version of SignalR I can no longer use GlobalHost or IConnectionManager to get a reference to a hub context. I can use DI to get a reference to the hub context in a controller without any problems.

public BroadcastController(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}

But I need to know how to do it outside of a controller.

Upvotes: 0

Views: 1347

Answers (1)

Mohsin Mehmood
Mohsin Mehmood

Reputation: 4236

You can inject IHubContext in any class other than contoller. Check the code snippet below:

 public class NotificationListnerExtension : INotificationListnerExtension
    {
        private readonly IHubContext<Notification> _notificationHubContext; 

        public NotificationListnerExtension(
            IHubContext<Notification> notificationHubContext)
        {
            _notificationHubContext = notificationHubContext;                
        }
}

Upvotes: 1

Related Questions