ASP.NET Core 3.0 re-platformed the WebHostBuilder
on top of the generic IHost
abstraction, so that Kestrel runs in an IHostedService
. Any IHostedService
implementations you add to Startup.ConfigureServices()
are started before the GenericWebHostService
that runs Kestrel. But what if you need to start your IHostedService
after the middleware pipeline has been created, and your application is handling requests?
In this post I show how to add an IHostedService
to your application so that it runs after the GenericWebHostSevice
. This only applies to ASP.NET Core 3.0+, which uses the generic web host, not to ASP.NET Core 2.x and below.
tl;dr;_ As described in the documentation, you can ensure your
_IHostedService_
runs after the_GenericWebHostSevice_
by adding an additional_ConfigureServices()_
to the_IHostBuilder_
in Program.cs, after_ConfigureWebHostDefaults()_
._
IHost
starts your IHostedService
s firstI’ve discussed the ASP.NET Core 3.x startup process in detail in a previous post, so I won’t cover it again here other than to repeat the following image:
This shows the startup sequence when you call RunAsync()
on IHost
(which in turn calls StartAsync()
). The important parts for our purposes are the IHostedService
s that are started As you can see from the above diagram, your custom IHostedService
s are started before the GenericWebHostSevice
that starts the IServer
(Kestrel) and starts handling requests.
You can see an example of this by creating a very basic IHostedServer
implementation:
public class StartupHostedService : IHostedService
{
private readonly ILogger _logger;
public StartupHostedService(ILogger<StartupHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting IHostedService registered in Startup");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("StoppingIHostedService registered in Startup");
return Task.CompletedTask;
}
}
#asp.net core #dependency injection #generic host #hostbuilder