内容目录
public class TestNoopHostLifetime : IHostLifetime
{
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("程序停止");
return Task.CompletedTask;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("程序启动");
return Task.CompletedTask;
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddSingleton<IHostLifetime, TestNoopHostLifetime>();
//services.AddSingleton<IServer, TestServer>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
也可以注册事件:
var applicationLifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
applicationLifetime.ApplicationStopping.Register(() =>
{
AsyncHelper.RunSync(() => application.ShutdownAsync());
});
applicationLifetime.ApplicationStopped.Register(() =>
{
application.Dispose();
});
文章评论