Request Lifecycle
- Introduction
- Lifecycle Overview
- The Middleware Pipeline
- The Service Scope
- Complete Example: Observe a Request
Introduction
When using any tool in the "real world", you feel more confident if you understand how that tool works. This page gives a high-level overview of how a DotBlaze application starts and how a request travels through it. If some terms are unfamiliar, keep reading; the other pages explain them in detail.
DotBlaze does not have its own HTTP kernel. A DotBlaze application is an ASP.NET Core WebApplication, and DotBlaze configures it the Laravel way.
Lifecycle Overview
First Steps
The entry point is Program.cs. It is the equivalent of Laravel's public/index.php and artisan at the same time:
var app = DotBlaze.Application.Create(args);
app.Run();
public partial class Program;Application.Create builds the whole application. Run then either starts the web server or runs a console command.
Configuration and Services
Application.Create first creates a WebApplicationBuilder, then:
- Loads
.envfrom the application root into the process environment (existing variables are not overwritten). - Runs every
ConfigFileclass (theconfig/*.csfiles) and adds the result as the lowest-priority configuration source. See Configuration. - Registers DotBlaze's services: Data Protection,
IHttpClientFactory, hashing, the database manager, migrator and seeder runner, the event dispatcher, the queue and worker, storage, routing, and authentication. - Registers MVC with DotBlaze's conventions: views under
resources/views, the model binder forModel<T>route parameters, theFormRequestvalidation filter, automatic CSRF validation, JSON settings for models, and session-backed authentication.
Service Providers
Next, DotBlaze finds every non-abstract class that extends Provider in your application assembly, creates them in order of their full type name, and calls Register(services, config) on each one. This is where your application adds its own services.
DotBlaze then builds the WebApplication, sets up the middleware pipeline, and calls Boot(app) on each provider in the same order. Boot runs inside a service scope, so facades such as Route, Event, and Config already work there. See Service Providers.
Routing
The template's RouteServiceProvider calls Web.Map() from routes/web.cs during Boot. Each Route.Get(...), Route.Post(...), and so on records a route definition. After every provider has booted, DotBlaze maps all recorded routes to MVC controller endpoints. See Routing.
Web Server or Console Command
If the first command line argument is not an option (--x or x=y) it is treated as a command name; for a built-in command (for example dotblaze migrate), Run executes that command inside a new service scope, sets the process exit code, and returns. The web server is not started, so hosted services (including the in-app queue worker) do not run. See Console Commands.
Otherwise Run starts the web server and begins handling requests.
The Middleware Pipeline
Every HTTP request passes through this pipeline, in order:
- Developer exception page, in debug mode only (
DevelopmentandTestingby default), which shows the stack trace of an unhandled exception. - Static files from
wwwroot, and files on thepublicdisk at itsurl(default/storage). - Method override: a form field named
_methodturns aPOSTintoPUT,PATCH, orDELETE, like Laravel's@method. - Service scope: the request's services become the active scope for facades (see below).
- Exception handler: reports exceptions and renders error responses.
Abort(...)uses the supplied status,ModelNotFoundExceptionbecomes404, andAuthorizationExceptionbecomes403. Debug mode shows the developer exception page for HTML errors. See Error Handling. - Routing, which selects the endpoint.
- Authentication: the auth cookie is read and the current user is loaded, so
Auth.User<T>()works. - Authorization.
- Route middleware: the
auth,guest, or application aliases attached to the matched route. See Middleware. - The controller action, wrapped in MVC filters: CSRF validation for unsafe methods and
FormRequestvalidation.
Middleware you add with app.Use(...) in a provider's Boot method runs after step 9, just before the controller.
The Service Scope
Facades need to know which services to use. ASP.NET Core creates a dependency injection scope per request; step 4 of the pipeline stores it in ServiceScope, an AsyncLocal value that flows with the request's async code. Every facade call during that request resolves its service from that scope, so scoped services (such as the database context) are shared within one request and disposed when it ends.
Outside a request, such as in a queue job, a console command, or a seeder, DotBlaze creates a scope with ServiceScope.Run(...) before running your code. Your own background code does the same. See Facades.
Complete Example: Observe a Request
Create this provider in a Blog application. It has a unique name so it can coexist with the generated providers:
// app/Providers/RequestTraceProvider.cs
using DotBlaze;
using Microsoft.AspNetCore.Builder;
namespace Blog.Providers;
public class RequestTraceProvider : Provider
{
public override void Boot(WebApplication app)
{
app.Use(async (context, next) =>
{
var id = context.TraceIdentifier;
DotBlaze.Context.Add("request_id", id);
Log.Info($"Starting {context.Request.Method} {context.Request.Path} [{id}]");
try
{
await next(context);
}
finally
{
Log.Info($"Leaving request pipeline [{id}]");
}
});
}
}Run dotblaze serve and open /. Expect two log messages with the same identifier around the action. A second request receives a different identifier and a new context repository. Requests completed by earlier middleware (for example static assets or a guest rejected by auth) do not reach this provider middleware.
The finally message describes leaving this middleware, not a guaranteed successful response: an exception can still be rendered by the outer exception handler. This is why application services and facade calls belong inside the request delegate, while service registrations belong in Register.