I have an .NET Core 3.1 app that serves an endpoint that describes health of application, and an IHostedService crunching through data in database.
There's a problem though, the worker function of HostedService starts processing for a long time, and as result the Configure()
method in Startup is not called and the /status
endpoint is not running.
I want the /status
endpoint to start running before the HostedService kicks off. How do i start the endpoint before the Hosted Service?
Sample code
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");
});
});
}
}
The HostedService
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;
}
}
I tried to explore adding the HostedService in Configure()
, but app.ApplicationServices
is a ServiceProvider hence readonly.
ExecuteAsync
into a seperate method and thenawait
that in ExecuteAsync ieawait DoWork(stoppingToken)
. You can also try placingawait Task.Delay(1);
as the first line. Creation of services are blocked on until they become asynchronous. I'd expect it to become so immediately at your first await, but similar examples in the docs use the first mechanism I suggest – DielectricProgram.cs
instead of inside theStartup.ConfigureServices
. Otherwise the server didn't actually start. – Jeter