asp.net core api 中 IHostedService 的正常关闭

chr*_*00r 5 c# asp.net-core asp.net-core-webapi

我的 asp net core api 项目遇到问题。我尝试实现一些基本检查(例如数据库连接),如果检查失败,我想正常关闭我的应用程序。
为此,我实现了该接口并将其添加为我的类 ( ) 的方法IHostedService中的 HostedService 。ConfigureServicesstartupservices.AddHostedService<MyService>();

MyService 的实现StartAsync目前看起来是这样的:

public Task StartAsync(CancellationToken cancellationToken){
    applicationLifetime.StopApplication();
}
Run Code Online (Sandbox Code Playgroud)

该变量applicationLifetime是类型的IHostApplicationLifetime并且是从 DI-Service 注入的。我得到以下异常:

[15:58:42 FTL] Unable to start Kestrel.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
Unhandled exception. System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Program.Main(String[] args) in Program.cs:line 31
   atProgram.<Main>(String[] args)
Run Code Online (Sandbox Code Playgroud)

我的 Programm.cs 类的第 31 行是 main 方法的一部分await host.RunAsync();

我的目标是在其他托管服务运行或 api 可以处理请求之前停止应用程序。