Application startup code in ASP.NET Core

Kyle B. picture Kyle B. · Aug 19, 2016 · Viewed 14.5k times · Source

Reading over the documentation for ASP.NET Core, there are two methods singled out for Startup: Configure and ConfigureServices.

Neither of these seemed like a good place to put custom code that I would like to run at startup. Perhaps I want to add a custom field to my DB if it doesn't exist, check for a specific file, seed some data into my database, etc. Code that I want to run once, just at app start.

Is there a preferred/recommended approach for going about doing this?

Answer

Professor of programming picture Professor of programming · Jan 3, 2018

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