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.
Best practise: application startup code in ASP.NET Core web app

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?
2 answers
Sort by: Most helpful
-
-
Zhi Lv - MSFT 32,931 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