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

Jozef 6 Reputation points
2023-07-28T15:47:18.28+00:00

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,024 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 52,826 Reputation points
    2023-07-28T15:55:06.0433333+00:00

    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
    2023-08-01T02:59:48.5533333+00:00

    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

    0 comments No comments