wasAsked.

Lifecycle of .Net core application

HCA Healthcare · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

"Lifecycle" can mean the application's startup and shutdown, or the lifecycle of a single request. A good answer covers both. 1. Application startup - Program.cs creates a builder: WebApplication.CreateBuilder(args). - Configuration is loaded in order: appsettings.json, appsettings.{Environment}.json, user secrets (in Development), environment variables, command-line arguments. Later sources override earlier ones. - Logging is configured, and services are registered in the dependency injection container (builder.Services). - builder.Build() creates the app and the service provider. - The middleware pipeline and endpoints are configured (app.Use..., app.Map...). - app.Run() starts the host: hosted services (IHostedService and BackgroundService) start, Kestrel begins listening, and IHostApplicationLifetime.ApplicationStarted fires. 2. Request lifecycle - Kestrel receives the HTTP request (possibly behind IIS, Nginx or a load balancer) and creates an HttpContext. - A DI scope is created for the request. - The request flows through middleware in registration order: exception handling, HTTPS redirection, static files, routing, CORS, authentication, authorization, and so on. - Routing selects an endpoint. For MVC controllers: filters (authorization, resource, action), model binding and validation, action execution, result filters, then the result is written. - The response travels back through the middleware in reverse order. - The request scope ends and scoped services (such as DbContext) are disposed. 3. Shutdown - On SIGTERM or Ctrl+C, ApplicationStopping fires, Kestrel stops accepting new connections, in-flight requests get time to finish (HostOptions.ShutdownTimeout), hosted services' StopAsync runs, ApplicationStopped fires, and singletons are disposed. Practical points: use IHostApplicationLifetime to hook startup and shutdown events, honour cancellation tokens in background services for graceful shutdown, and remember that middleware order defines request behaviour.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics