3

I've created a new ASP.NET 6 web app. I want to periodically broadcast a message through a SignalR hub, from the server. How can I access the hub from the server? Other answers suggest using GlobalHost but it belongs to a deprecated version of SignalR

Example code from web app Program.cs:

app.MapHub<SiteLayoutHub>("hubs/site");

app.Run();

Task.Factory.StartNew(async () =>
{
    var hub = GetSiteLayoutHub(); // How can I get this hub?
    while (true)
    {
        var uiState = GetUIState();
        await hub.SendUIUpdateMessage(uiState);
        Thread.Sleep(500);
    }
});

SiteLayoutHub.cs:

public class SiteLayoutHub : Hub
{
    public async Task SendUIUpdateMessage(UIState uiState)
    {
        await Clients.All.SendAsync("UIUpdateMessage", uiState);
    }
}
2
  • You'll need to create a .Net client to run on the server side. I'd close it after you're finished. Or map another hub endpoint dedicated only to this client. Commented Jan 30, 2023 at 16:54
  • 2
    learn.microsoft.com/aspnet/core/signalr/… or learn.microsoft.com/aspnet/core/signalr/… Note: You do not (and should not) get access to a Hub in background tasks, you get access to an interface that lets you send messages to clients. Commented Jan 31, 2023 at 0:39

1 Answer 1

5

These are all of the pieces required:

using Microsoft.AspNetCore.SignalR;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();
builder.Services.AddHostedService<UIUpdateService>();

var app = builder.Build();

app.MapHub<SiteLayoutHub>("hubs/site");

app.Run();

public class SiteLayoutHub : Hub { }

public class UIUpdateService : BackgroundService
{
    private readonly IHubContext<SiteLayoutHub> _hubContext;
    public UIUpdateService(IHubContext<SiteLayoutHub> hubContext)
    {
        _hubContext = hubContext;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            var uiState = GetUiState();
            await _hubContext.Clients.All.SendAsync("UIState", uiState);
        }
    }

    private object GetUiState()
    {
        throw new NotImplementedException();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, much appreciated. For anyone else looking for this answer, you might find this MSDN page useful: learn.microsoft.com/en-us/aspnet/core/fundamentals/host/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.