Best practise: application startup code in ASP.NET Core web app

Jozef 6 Reputation points


what is the best practise for running startup code (eg. downloading initial data from S3) in an ASP.NET Core web app?

Is there built-in interface/service we can extended so the app knowns it is not ready yet to accept connections?

A set of technologies in the .NET Framework for building web applications and XML web services.
4,024 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce ( 52,826 Reputation points

    As long as you call the code before app.Run() it will complete before requests are accepted. If async, be sure to use await keyword.

    0 comments No comments

  2. Zhi Lv - MSFT 29,986 Reputation points Microsoft Vendor

    Hi @Jozef

    You can create a custom middleware to initial the data and call it before the app.Run() method. Or you can create a service, and then resolve the service at app start up. Code like this:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddScoped<IMyDependency, MyDependency>();
    var app = builder.Build();
    using (var serviceScope = app.Services.CreateScope())
        var services = serviceScope.ServiceProvider;
        var myDependency = services.GetRequiredService<IMyDependency>();
        myDependency.WriteMessage("Call services from main");
    app.MapGet("/", () => "Hello World!");

    More detail information, see Dependency injection in ASP.NET Core and the seed initializer sample.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,


    0 comments No comments