ASP.NET Core 注册主机启动、停止事件

2022年6月24日 2284点热度 2人点赞 0条评论
内容目录
    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>();
                });

file

也可以注册事件:

        var applicationLifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();

        applicationLifetime.ApplicationStopping.Register(() =>
        {
            AsyncHelper.RunSync(() => application.ShutdownAsync());
        });

        applicationLifetime.ApplicationStopped.Register(() =>
        {
            application.Dispose();
        });

痴者工良

高级程序员劝退师

文章评论