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

1.1k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER
var hubContext = app.ApplicationServices.GetService<IHubContext<Notification>>

That resolved my issue.

0
On

I design my class as below.

public class NotificationHub : Microsoft.AspNetCore.SignalR.Hub
{
    public static IHubContext<NotificationHub> Current { get; set; }
}

In your Startup class

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    NotificationHub.Current = app.ApplicationServices.GetService<IHubContext<NotificationFromServerHub>>();

}

So, you can use as like this from anywhere.

public class MyBizClass
{
    public void DoSomething()
    {
        NotificationHub.Current.MyMethod(...);
    }
}