我有一个 .NET Core 3.1 应用程序,它提供一个描述应用程序运行状况的端点,以及一个 IHostedService 处理数据库中的数据。但是有一个问题,HostedService的worker函数开始处理很长时间,导致Startup中的Configure()
方法没有被调用,/status
端点也没有运行。
我希望/status
端点在 HostedService 启动之前开始运行。如何在托管服务之前启动端点?
示例代码
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<SomeHostedProcessDoingHeavyWork>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/status", async context =>
{
await context.Response.WriteAsync("OK");
});
});
}
}
托管服务
public class SomeHostedProcessDoingHeavyWork : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await MethodThatRunsForSeveralMinutes();
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
private async Task MethodThatRunsForSeveralMinutes()
{
// Process data from db....
return;
}
}
我试图探索在 中添加 HostedService Configure()
,但app.ApplicationServices
它是一个 ServiceProvider,因此是只读的。