How to send a message outside the controller?

I need to send information to the connected clients outside the HUB.

Here my class :

public static class Notification{
  public static void SendMessage(){
    //... Do some stuff
    MyHub.Clients.All.SendAsync("sendInfo");
  }
}

How to instantiate HUB?

Upvotes: 2

Views: 820

Answers (2)

Kiril1512
Kiril1512

Reputation: 3621

You do as @Brando Zhang posted above or just inject the Hub in to your controller or manager like:

Controller

private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.HttpContext.RequestServices.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}

Other

private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.serviceProvider.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}

PS: It is recomended to inject the HubContext and not the hub directly.

Upvotes: 0

Brando Zhang
Brando Zhang

Reputation: 27987

As far as I know, you could use IHubContext service to send the service message outside the hub.

If you have register the service inside the ConfigureServices in startup.cs, then you could access an instance of IHubContext via dependency injection.

        services.AddSignalR();

E.g Inject an instance of IHubContext in a controller.

public class HomeController : Controller
{
    private readonly IHubContext<NotificationHub> _hubContext;

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

Now, with access to an instance of IHubContext, you can call hub methods as if you were in the hub itself.

public async Task<IActionResult> Index()
{
    await _hubContext.Clients.All.SendAsync("Notify", $"Home page loaded at: {DateTime.Now}");
    return View();
}

More details ,you could refer to this article.

Upvotes: 0

Related Questions