Skip to content

Implement IApplicationLifetime to detect application shutdown and gracefully close connections  #18

@timbellomo

Description

@timbellomo

Some thoughts on graceful shutdown, either for app pool recycle or server reboot. Event can fire to notify clients.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddSingleton<IApplicationLifetime>(provider =>
    {
        var lifetime = provider.GetService<IHostApplicationLifetime>();
        return lifetime;
    });
}

then

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApplicationLifetime lifetime)
{
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<DashboardHub>("/dashboardHub", options =>
        {
            options.AddHubOptions<DashboardHub>(o =>
            {
                o.AddClient lifetime);
            });
        });
    });
}

then

public class DashboardHub: Hub
{
    private readonly IApplicationLifetime _lifetime;
    private static CAD _cad;

    public DashboardHub(IApplicationLifetime lifetime, CAD cad)
    {
        _lifetime = lifetime;
        _lifetime.ApplicationStopping.Register(OnStopping);
        _cad = cad;
    }

    private void OnStopping()
    {
        // Code to handle the shutdown goes here
    }
}

There may be better ways to handle this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions