π ASP.NET Core Application Lifecycle: A Behind-the-Scenes Tour
nderstanding the ASP.NET Core lifecycle
is critical if you want to build efficient, scalable, and maintainable web
applications. From app startup to handling each HTTP request, ASP.NET Core
gives you fine control over how your application behaves.
In this post, we’ll explore:
- π What the application lifecycle is
- π Startup process: Program.cs and Startup.cs
- π Middleware pipeline and request handling
- π Dependency Injection and Service Lifetime
- π§Ό Application shutdown lifecycle
π§ What Is the Application Lifecycle?
The ASP.NET Core lifecycle refers to the
flow of an application from:
- Application startup
- Request processing
- Service instantiation
- Response generation
- Application shutdown
This cycle ensures your app is properly
configured, requests are handled efficiently, and resources are cleaned up.
π Application Startup
The startup process in ASP.NET Core happens in
the Program.cs file (and formerly also Startup.cs).
π Program.cs (ASP.NET Core 6+)
csharp
var builder =
WebApplication.CreateBuilder(args);
// Configure services
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>();
var app = builder.Build();
// Configure middleware
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
Think of Program.cs as the bootstrapper of
your app — it builds the application host, registers services, and wires up
middleware.
π§± Middleware Pipeline
ASP.NET Core uses a middleware pipeline
to process HTTP requests. Each middleware can:
- Inspect/modify the request
- Pass control to the next
middleware (await next())
- Handle/modify the response
Example Pipeline Flow:
csharp
app.UseMiddleware<RequestLoggingMiddleware>(); // Logs incoming requests
app.UseRouting(); // Determines
endpoint
app.UseAuthorization(); // Checks auth rules
app.MapControllers(); // Executes
controller action
Order matters: Each middleware component runs
in the order it’s added.
π§ͺ Request Processing Lifecycle
Here's what happens when an HTTP request
hits your ASP.NET Core app:
- Kestrel Server receives the request.
- ASP.NET Core creates an HttpContext
object.
- The request enters the middleware
pipeline.
- Routing middleware finds the
matching endpoint.
- Dependency Injection resolves
the required controller and services.
- The controller action is
executed.
- The response travels
back through middleware.
- The result is sent back to
the client.
π Dependency Injection (DI) Lifecycle
ASP.NET Core is built with DI in mind. Services
are registered with different lifetimes:
|
Lifetime |
Description |
|
Singleton |
One instance for the whole app lifetime |
|
Scoped |
One instance per HTTP request |
|
Transient |
A new instance every time it's requested |
csharp
builder.Services.AddSingleton<IMySingletonService,
MyService>();
builder.Services.AddScoped<IMyScopedService,
MyService>();
builder.Services.AddTransient<IMyTransientService,
MyService>();
Choose the right lifetime to avoid memory leaks
or service conflicts.
π¦ Application Configuration Flow
Program.cs Order of Execution:
- WebApplication.CreateBuilder()
→ sets up config, logging, DI
- builder.Services → register
services
- builder.Build() → builds the
web host
- Middleware pipeline setup
- app.Run() → starts listening
for requests
Older Style (Startup.cs):
If using ASP.NET Core 3.1/5.0:
csharp
public class Startup
{
public
void ConfigureServices(IServiceCollection services) { }
public
void Configure(IApplicationBuilder app, IWebHostEnvironment env) { }
}
π§Ό Application Shutdown
ASP.NET Core handles shutdown gracefully:
- Cancels hosted services
- Disposes of DI-scoped objects
- Logs shutdown events
Graceful Cleanup Example
csharp
public class CleanupHostedService : IHostedService,
IDisposable
{
public
Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("App starting...");
return
Task.CompletedTask;
}
public
Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("App stopping...");
return
Task.CompletedTask;
}
public
void Dispose()
{
Console.WriteLine("Cleanup resources...");
}
}
π§ Lifecycle Summary
|
Phase |
Responsibility |
|
Startup |
Configure services and middleware |
|
Request Handling |
Build HttpContext and run middleware pipeline |
|
Controller Action |
Execute logic with DI-injected services |
|
Response |
Return result back to client |
|
Shutdown |
Dispose services and resources gracefully |
⚙️
Tools to Monitor Lifecycle
- Serilog / NLog: Log app start/stop and requests
- Middleware: Track requests/responses
- MiniProfiler: Measure lifecycle performance
π§ Final Thoughts
Understanding the ASP.NET Core lifecycle
helps you:
✅
Register services properly
✅ Control request processing
✅ Handle edge cases like cleanup and shutdown
✅ Debug and optimize performance
Comments
Post a Comment