using HRM.UI.Realtime.Jobs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace HRM.UI.Realtime
{
///
/// Real-time (SignalR) and background-job wiring, kept out of Startup:
/// services.AddRealtime(...) in ConfigureServices, endpoints.MapRealtime() inside UseEndpoints.
///
public static class RealtimeSetup
{
/// The hub's URL. It sits under /api so the Angular dev proxy and IIS treat it like every other API call.
public const string HubPath = "/api/hubs/app";
public static IServiceCollection AddRealtime(this IServiceCollection services, IConfiguration configuration,
IWebHostEnvironment environment)
{
IConfigurationSection section = configuration.GetSection("Realtime");
services.Configure(section);
RealtimeSettings settings = section.Get() ?? new RealtimeSettings();
services.AddSignalR(options =>
{
options.KeepAliveInterval = TimeSpan.FromSeconds(Math.Max(5, settings.KeepAliveSeconds));
options.ClientTimeoutInterval = TimeSpan.FromSeconds(Math.Max(10, settings.ClientTimeoutSeconds));
options.MaximumReceiveMessageSize = Math.Max(4, settings.MaxReceiveMessageKB) * 1024L;
options.EnableDetailedErrors = environment.IsDevelopment();
})
// Same JSON as the REST API (AddNewtonsoftJson), so a BO looks identical over both.
.AddNewtonsoftJsonProtocol();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(provider => provider.GetRequiredService());
services.AddHostedService(provider => provider.GetRequiredService());
return services;
}
public static IEndpointRouteBuilder MapRealtime(this IEndpointRouteBuilder endpoints)
{
endpoints.MapHub(HubPath, options =>
{
// Close the connection when the JWT it was opened with expires; the browser reconnects with the
// current cookie, or stops if the user is signed out.
options.CloseOnAuthenticationExpiration = true;
});
return endpoints;
}
}
}