Sometimes it is useful to know when the host web application has started listening for calls to web site pages and also when it is stopping listening and completely stopped listening. You can register for these events in .NET applications
/// <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 that kind of pattern/behaviour is required in your application.
/// 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
}
}
Usage, simply inject it to your dependency injection services
public static class DependencyInjection
{
public static IServiceCollection ConfigureServices(this IServiceCollection services)
{
// Add application services.
services.AddSingleton<IRsgConfiguration, RsgConfiguration>();
services.AddSingleton<IHostedService, WebApplicationLifetimeEvents>();
...
No comments:
Post a Comment