asp.net core:IApplicationLifetime.ApplicationStopping 未触发

lio*_*mor 6 c# asp.net-core asp.net-core-middleware

我看到了一些关于 IApplicationLifetime 以及应用程序启动和停止时触发执行的方式的文章,但我可能错过了一些东西,因为它没有被触发。这是我的解决方法:我打开了一个项目模板Container Application for kubernetes, asp.net core 2.2

Program.cs 看起来与创建时一样:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Kubernetes1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs 如下所示:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Kubernetes1
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
            appLifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping called"));
            appLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped called"));
            app.Run(async (context) =>
            {
                Console.WriteLine("AAA");
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里想做的就是在 cmd 中运行应用程序,然后停止它并看到控制台中打印出 2 行:

  1. 应用程序停止调用
  2. ApplicationStopped 调用我没能做到这一点。有任何想法吗?

pok*_*oke 4

在另一个 cmd 窗口中我输入:Get-Process -Name *dotnet* | Stop-Process

Stop-Process将终止该进程,跳过应用程序可能具有的任何正常关闭行为。

当IApplicationLifetime谈到应用程序停止时,它指的是应用程序被正常关闭。有几种方法可以触发此操作,具体取决于应用程序的启动方式:

  • 当应用程序在控制台中运行时:CTRL + C. 例如,当运行dotnet run或直接运行已编译的可执行文件时。
  • 当应用程序在 IIS 中运行时:停止网站或应用程序池。
  • 当应用程序作为 Windows 服务运行时:停止服务。