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

社会主义新天地 提交于 2020-01-06 06:03:45

问题


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.


回答1:


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;                
        }
}


来源:https://stackoverflow.com/questions/50182196/how-do-you-get-a-reference-to-an-asp-net-core-signalr-hub-context-outside-of-a-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!