Search code examples
signalrsignalr-hubasp.net-core-signalrsignalr-backplanesignalr-2

Get HubContext from outside of Hub using Aspnetcore.signalr libray (not from Controller)


I am developing SignalR service using AspNetCore.SignalR.

Following is my Hub:

public class NotificationHub : Microsoft.AspNetCore.SignalR.Hub
    {
        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
        }
    }

Following is Another Context class that i have created to invoke Hub's method on client side:

public class NotificationHubContext
    {
        private readonly IHubContext<NotificationHub> _context;

        public NotificationHubContext(IHubContext<NotificationHub> context)
        {
            _context = context;
        }

        public async Task Broadcast(string groupId, string eventName, object data)
        {
            await _context.Clients.Group(groupId).SendAsync(eventName, data);
        }
    }

I would like to Inject reference of NotificationContext class into my own IoC Container so I can just resolve it and call a BroadCast method on it and it should handle sending messages to clients.

I am using Service Bus to listen for messages from another part of the system, once I receive a message from Queue, I would like to notify Connected clients using HubContext from QueueHandler.

Assembly Info


Solution

  • var hubContext = app.ApplicationServices.GetService<IHubContext<Notification>>
    

    That resolved my issue.