Share via

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

Jozef 6 Reputation points
Jul 28, 2023, 3:47 PM

Hi,

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?

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

2 answers

Sort by: Oldest
  1. Bruce (SqlWork.com) 72,356 Reputation points
    Jul 28, 2023, 3:55 PM

    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 33,161 Reputation points Microsoft External Staff
    Aug 1, 2023, 2:59 AM

    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!");
    
    app.Run();
    

    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,

    Dillion

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.