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()_._

The generic IHost starts your IHostedServices first

I’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:

Sequence diagram for Host.StartAsync()This shows the startup sequence when you call RunAsync() on IHost (which in turn calls StartAsync()). The important parts for our purposes are the IHostedServices that are started As you can see from the above diagram, your custom IHostedServices 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

Controlling IHostedService execution order in ASP.NET Core 3.x
6.70 GEEK