April 28, 2022

Sample HostApplicationLifetime Events Class for ASP .Net Core

There are some environments where you are using an underlying technology to assist you, for example, WPF, Win Forms, and ASP.NET. It is useful sometimes in these environments to be able to initialise application code just after the underlying technology has been initialised, and have some termination/finalisation code invoked just before the underlying technology is unwound.

In my case, I had to call a service that started a FileSystemWatcher when the web hosting service started and stopped it when the web hosting service was about to end. These events are very important in the hosts lifetime, so I added logging to record them. I also used my own application configuration file which was beyond that provided by the ASP.Net Core services, but the location of which was set within it.

Here is a class to do this in .NET Core:
/// <summary>
/// This class tells you when the Web Application 
/// Starts (just prior to listening for web requests) 
/// and Stops and has Stopped, so you can start things up 
/// and shut them down at the end if they fit that kind of pattern
/// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0#ihostapplicationlifetime
/// </summary>
internal class WebApplicationLifetimeEvents : IHostedService
{
    private readonly ILogger _logger;
    private readonly IHostApplicationLifetime _appLifetime;
    private readonly IWebHostEnvironment _webhostEnvironment;


    public WebApplicationLifetimeEvents(
        ILogger<WebApplicationLifetimeEvents> logger,
        IHostApplicationLifetime appLifetime,
        IWebHostEnvironment webhostEnvironment,
        )
    {
        
        _logger = logger;
        _appLifetime = appLifetime;
        _webhostEnvironment = webhostEnvironment;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _appLifetime.ApplicationStarted.Register(OnStarted);
        _appLifetime.ApplicationStopping.Register(OnStopping);
        _appLifetime.ApplicationStopped.Register(OnStopped);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void OnStarted()
    {
        _logger.LogInformation("OnStarted has been called.");
         // Perform post-startup activities here:
        try
        {

        }
        catch (Exception ex)
        {
            _logger.LogError($"Exception in OnStarted {ex}");
            throw;
        }
    }

    private void OnStopping()
    {
        _logger.LogInformation("OnStopping has been called.");

        // Perform on-stopping activities here
    }

    private void OnStopped()
    {
        _logger.LogInformation("OnStopped has been called.");

        // Perform post-stopped activities here
    }
}
Then to use the service:
services.AddSingleton<IHostedService, WebApplicationLifetimeEvents> ();