Hosting & Application Builder¶
LambdaApplication.CreateBuilder() mirrors ASP.NET Core’s WebApplication.CreateBuilder() but is tuned for Lambda’s execution model. This guide explains what the builder does for you, how to customize it, and how the hosting infrastructure composes lifecycle hooks, middleware, and handlers.
Builder Defaults¶
Calling LambdaApplication.CreateBuilder() assembles a standard .NET host with Lambda-friendly defaults:
- Configuration sources – Adds
appsettings.json,appsettings.{Environment}.json, user secrets (development),AWS_andDOTNET_prefixed environment variables, and ambient environment variables. The resultingConfigurationManageris exposed viabuilder.Configuration. - Environment & content root – Sets
IHostEnvironment.ApplicationNamefromAWS_LAMBDA_FUNCTION_NAME(when available) and resolves the content root by honoringDOTNET_CONTENTROOT,AWS_LAMBDA_TASK_ROOT, or falling back toDirectory.GetCurrentDirectory(). - Logging – Registers console logging with activity tracking enabled. In Development, scope validation is turned on so singleton/scoped misuse throws during build.
- Dependency injection – Every call to
builder.Serviceshits the standardIServiceCollection. Onbuilder.Build(), aws-lambda-host registers: ILambdaInvocationBuilderFactory,ILambdaOnInitBuilderFactory, andILambdaOnShutdownBuilderFactoryso lambda-specific pipelines can be composed later.LambdaHostedService,ILambdaHandlerFactory, feature collections, andILambdaBootstrapOrchestrator.- Default implementations of
ILambdaSerializer(System.Text.Json) andILambdaCancellationFactoryunless you already registered your own viaTryAddLambdaHostDefaultServices().
Most applications can rely entirely on CreateBuilder() + builder.Build()—just add services, middleware, handlers, and call await lambda.RunAsync();.
Customizing the Builder¶
Use LambdaApplicationOptions when you need to tweak how the builder initializes:
When DisableDefaults = true, you’re responsible for adding configuration providers, logging, and environment metadata before calling builder.Build(). This mode is useful for specialized hosting scenarios (custom service provider factory, integration tests, CLI applications) but most Lambda projects should keep the defaults.
Other customization hooks:
LambdaApplicationOptions.Args– Flow command-line arguments into configuration.builder.Services.ConfigureLambdaHostOptions(...)– Override runtime behavior (Init/Shutdown timeouts, invocation cancellation buffer, output formatting).builder.Services.AddLambdaSerializerWithContext<TContext>()– Swap the default serializer with a source-generated one (or register anyILambdaSerializermanually).- Register an
ILambdaHostContextAccessorif you need to resolveILambdaHostContextoutside handlers/middleware.
Build Phase¶
builder.Build() finalizes configuration and returns a LambdaApplication that implements IHost, ILambdaInvocationBuilder, ILambdaOnInitBuilder, and ILambdaOnShutdownBuilder. During build:
TryAddLambdaHostDefaultServices()ensures a serializer and cancellation factory exist.- A standard
IHostis constructed viaHost.CreateEmptyApplicationBuilder+ your service registrations. - The
LambdaApplicationwrapper caches factories for the invocation, init, and shutdown builders.
After build you can still call:
lambda.UseMiddleware(...),lambda.MapHandler(...)– Compose the invocation pipeline.lambda.OnInit(...),lambda.OnShutdown(...)– Register lifecycle hooks.lambda.Properties[...]– Store metadata consumed by middleware or handlers.
Runtime Execution¶
The LambdaHostedService orchestrates execution when you call await lambda.RunAsync();:
- The hosted service creates a linked
CancellationTokenSourceso it can cancel the loop during shutdown. - Middleware and the handler delegate are composed via
ILambdaHandlerFactory, which callsConfigureHandlerBuilder(injecting your registered middleware and the default envelope middleware). - OnInit and OnShutdown builders are configured, including the optional
ClearLambdaOutputFormattinghandler. - The bootstrap (
ILambdaBootstrapOrchestrator) starts polling the Lambda Runtime API, invoking the composed handler for each event, and honoringLambdaHostOptions(cancellation buffers, shutdown durations). - When the runtime stops, the hosted service calls the aggregated shutdown handler and bubbles exceptions as
AggregateExceptionso you see every failure in logs.
Testing & Alternate Hosts¶
Because LambdaApplication implements IHost, you can start it outside Lambda, resolve services, and
stop it like any other generic host:
| Program.cs | |
|---|---|
For non-Lambda entry points (console apps, acceptance tests), combine StartAsync/StopAsync with
DisableDefaults = true if you want a trimmed-down host that reuses Lambda-ready middleware and
handlers.
Troubleshooting¶
| Issue | Cause | Fix |
|---|---|---|
InvalidOperationException: Lambda Handler is not set. |
builder.Build() succeeded but lambda.MapHandler(...) was never called. |
Register a handler before calling lambda.RunAsync(). |
AggregateException: Encountered errors while running OnInit handlers |
An OnInit delegate threw or returned false. |
Inspect inner exceptions; ensure handlers honor cancellation and only return false for fatal conditions. |
Graceful shutdown ... did not complete within the allocated timeout |
OnShutdown handlers exceeded LambdaHostOptions.ShutdownDuration - ShutdownDurationBuffer. |
Reduce work, increase shutdown duration, or skip optional cleanup. |
| Environment variables not loaded | You disabled defaults without re-adding builder.Configuration.AddEnvironmentVariables(). |
Re-add configuration sources or keep defaults. |
Related Guides¶
- Dependency Injection – Register services and understand lifetimes/scopes.
- Lifecycle Management – Deep dive into
OnInit/OnShutdownbehavior. - Configuration – Bind
LambdaHostOptionsand application settings. - Middleware – Build cross-cutting concerns with the invocation pipeline.