I got a problem with my asp net core api project. I try to implement some basic checks (for example db-connectivity) and if the check fails, I want to graceful shutdown my application.
For that, I implement the interface IHostedService
and add it as a hostedService within the ConfigureServices
method of my startup
class (services.AddHostedService<MyService>();
).
The StartAsync
implementation of MyService looks currently like that:
public Task StartAsync(CancellationToken cancellationToken){
applicationLifetime.StopApplication();
}
And the variable applicationLifetime
is of type IHostApplicationLifetime
and is injected from the DI-Service. I get the following exception:
[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)
and line 31 of my Programm.cs class is part of the main method with await host.RunAsync();
My goal is to stop the application before other hostedServices run or the api can handle requests.
question from:
https://stackoverflow.com/questions/65939753/graceful-shutdown-in-ihostedservice-in-asp-net-core-api 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…