在ASP.NET Core中,可以通过IHostApplicationLifetime接口来注册在应用程序关闭前或遇到致命错误时执行的操作。以下是示例代码:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var applicationLifetime = host.Services.GetService();
applicationLifetime.ApplicationStarted.Register(() =>
{
Console.WriteLine("Application started");
});
applicationLifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Application stopping");
// do something before shutdown
});
applicationLifetime.ApplicationStopped.Register(() =>
{
Console.WriteLine("Application stopped");
});
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
在上面的示例中,我们注册了三个事件:ApplicationStarted,ApplicationStopping和ApplicationStopped。ApplicationStarted事件在应用程序启动时被调用,ApplicationStopping事件在应用程序关闭之前被调用,在此事件中可以执行一些清理工作。ApplicationStopped事件在应用程序关闭后调用,可以执行一些后续处理工作。