Search code examples
c#asp.net-corestartup

Application startup code in ASP.NET Core


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?


Solution

  • Basically there are two entry points for such custom code at startup time.

    1.) Main method

    As a ASP.NET Core application has got the good old Main method as entry point you could place code before the ASP.NET Core startup stuff, like

    public class Program
    {
        public static void Main(string[] args)
        {
            // call custom startup logic here
            AppInitializer.Startup();
    
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
    
            host.Run();
        }
    }
    

    2.) Use your Startup class

    As you already stated in your question is the Configure and ConfigureServices a good place for your custom code.

    I would prefer the Startup class. From the runtime perspective it does not matter, if the call is called in startup or somewhere else before the host.Run() call. But from a programmer's point of view who is accustomed to the ASP.NET framework then his first look for such logic would be the Startup.cs file. All samples and templates put there the logic for Identity, Entity Framework initialization and so on. So as a convention I recommend to place the initialization stuff there.