Broadcasting from a hosted service with SignalR

· 2 min

Web applications often need work that runs in the background for their whole lifetime. Here, the application fetches data on an interval and pushes it to every connected client. The client side suits an observable pattern: subscribe, and handle new data as it arrives. SignalR does the pushing.

The hub

Register SignalR in ConfigureServices(IServiceCollection services):

services.AddSignalR();

Then map an endpoint for the hub in Configure(IApplicationBuilder app, IHostingEnvironment env):

app.UseSignalR(routes =>
{
    routes.MapHub<ChangeDataHub>("/changes");
});

From .NET Core 3.0, hubs are mapped with endpoint routing instead:

app.UseEndpoints(endpoints => endpoints.MapHub<ChangeDataHub>("/changes"));

ChangeDataHub inherits from Hub. Clients only listen, so it can stay empty:

public class ChangeDataHub : Hub
{
}

The background service

ASP.NET Core 2.1 added BackgroundService, an abstract IHostedService built for long-running work. You implement one method, ExecuteAsync. The host starts it without waiting for it to finish, and cancels its token on shutdown.

That matters. It's tempting to implement IHostedService directly and loop inside StartAsync, but StartAsync is meant to return once the service has started. A loop that never returns can hold up startup, and the token passed to StartAsync only signals that startup was cancelled. The loop would never see the app shutting down.

Register the service:

services.AddHostedService<ChangeDataListenerService>();

The service sends through IHubContext<ChangeDataHub>, the way to reach a hub's clients from outside the hub:

public class ChangeDataListenerService : BackgroundService
{
    private readonly IHubContext<ChangeDataHub> _hubContext;
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<ChangeDataListenerService> _logger;
    private readonly TimeSpan _delay = TimeSpan.FromSeconds(1);

    public ChangeDataListenerService(
        IHubContext<ChangeDataHub> hubContext,
        IServiceScopeFactory scopeFactory,
        ILogger<ChangeDataListenerService> logger)
    {
        _hubContext = hubContext;
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Return to the host before doing any synchronous work
        await Task.Yield();

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using (var scope = _scopeFactory.CreateScope())
                {
                    var dataManager = scope.ServiceProvider.GetRequiredService<DataManager>();
                    var data = dataManager.Get();

                    await _hubContext.Clients.All.SendAsync("TransferData", data, stoppingToken);
                }
            }
            catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogError(ex, "Failed to fetch or send updates");
            }

            await Task.Delay(_delay, stoppingToken);
        }
    }
}

Task.Yield is there because, before .NET 10, ExecuteAsync runs synchronously until its first await. dataManager.Get() is synchronous, so without the yield the first fetch would hold up startup.

Scoped dependencies

Hosted services are singletons. If DataManager depends on a DbContext, injecting it into the constructor would hold one DbContext for the lifetime of the app. A DbContext isn't thread-safe and is meant to be short-lived, so that leads to a whole host of problems.

Injecting IServiceScopeFactory instead and creating a scope on each iteration gives every run its own DbContext, disposed when the scope ends. It also keeps the constructor small, which helps in a larger, real-world service.

Errors

The try/catch stops one failed fetch from ending the loop. Without it, an exception in ExecuteAsync ends the service: in older versions it stops silently, and from .NET 6 it stops the whole host by default. The when filter lets cancellation through, so shutdown isn't logged as an error.