Application startup code in ASP.NET Core

This can be done by creating an IHostedService implementation and registering it using IServiceCollection.AddHostedService<>() in ConfigureServices() in your startup class.

Example

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

public class MyInitializer : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        // Do your startup work here

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        // We have to implement this method too, because it is in the interface

        return Task.CompletedTask;
    }
}
using Microsoft.Extensions.DependencyInjection;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<MyInitializer>();
    }
}

Notes

  • The main application will not be started until after your code has finished executing.
  • Constructor dependency injection is available to the IHostedService implementation.
  • I can recommend this blog post for more info, and an example of how to use async: https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-3/
  • For more background reading, see this discussion: https://github.com/dotnet/aspnetcore/issues/10137

I agree with the OP.

My scenario is that I want to register a microservice with a service registry but have no way of knowing what the endpoint is until the microservice is running.

I feel that both the Configure and ConfigureServices methods are not ideal because neither were designed to carry out this kind of processing.

Another scenario would be wanting to warm up the caches, which again is something we might want to do.

There are several alternatives to the accepted answer:

  • Create another application which carries out the updates outside of your website, such as a deployment tool, which applies the database updates programmatically before starting the website

  • In your Startup class, use a static constructor to ensure the website is ready to be started

Update

The best thing to do in my opinion is to use the IApplicationLifetime interface like so:

public class Startup
{
    public void Configure(IApplicationLifetime lifetime)
    {
        lifetime.ApplicationStarted.Register(OnApplicationStarted);
    }

    public void OnApplicationStarted()
    {
        // Carry out your initialisation.
    }
}