In ASP.NET Core 8, app.Run() is a blocking call that starts the web server and keeps it running until the application is shut down. Code placed directly after app.Run() won't execute during normal operation because the method doesn't return until the application stops.
Here are several approaches to execute code after the application has successfully started:
Using Application Lifetime Events
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Register a hosted service or use application lifetime events
app.Lifetime.ApplicationStarted.Register(() =>
{
// This runs after the application has fully started
Console.WriteLine("Application started successfully!");
// Your success delegate logic here
});
app.MapGet("/", () => "Hello World!");
app.Run(); // This blocks until shutdown
Using a Hosted Service
public class StartupService : IHostedService
{
private readonly ILogger<StartupService> _logger;
public StartupService(ILogger<StartupService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Application startup completed successfully!");
// Your success delegate logic here
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
// In Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<StartupService>();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Using RunAsync for Non-Blocking Execution
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
// Start the application asynchronously
var runTask = app.RunAsync();
// This executes after the server starts listening
Console.WriteLine("Server is now running!");
// Your success delegate logic here
// Wait for the application to complete
await runTask;
Using Application Events with Dependency Injection
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IMySuccessHandler, MySuccessHandler>();
var app = builder.Build();
// Get the service and register the callback
var successHandler = app.Services.GetRequiredService<IMySuccessHandler>();
app.Lifetime.ApplicationStarted.Register(() => successHandler.OnApplicationStarted());
app.MapGet("/", () => "Hello World!");
app.Run();
The ApplicationStarted event approach is typically the most appropriate for executing logic after the application has successfully started, as it fires once the server is ready to accept requests.