Application startup code in ASP.NET Core

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.
    }
}

Leave a Comment