Skip to content

Build AWS Lambda Functions with .NET Hosting Patterns

Main Build codecov Quality Gate Status License: MIT

AwsLambda.Host is a lightweight hosting framework for .NET developers who want the comfort of ASP.NET Core’s middleware, dependency injection, and lifecycle hooks inside AWS Lambda. Instead of wiring up scopes, serializers, and cancellation tokens by hand, you map strongly typed handlers and let the source-generated pipeline handle the plumbing. The result: less boilerplate, better testability, and handlers that feel like the rest of your .NET codebase.

Get Started Guides Examples (Coming Soon)


Why AwsLambda.Host?

Stop wiring up DI scopes, serializers, and cancellation tokens by hand. Ship features with patterns you already know, while still embracing Lambda’s execution model.

// ❌ Manual DI container setup
var services = new ServiceCollection();
services.AddScoped<IGreetingService, GreetingService>();

await using var rootProvider = services.BuildServiceProvider();

await LambdaBootstrapBuilder
    .Create<APIGatewayProxyRequest, APIGatewayProxyResponse>(
        async (request, context) =>
        {
            // ❌ Manual scope creation for each invocation
            using var scope = rootProvider.CreateScope();

            // ❌ Manual service resolution from scope
            var service = scope.ServiceProvider.GetRequiredService<IGreetingService>();

            // ❌ Manual cancellation token creation from context
            using var cts = new CancellationTokenSource(
                context.RemainingTime - TimeSpan.FromMilliseconds(500)
            );

            // ❌ Manual JSON deserialization
            var requestContent = JsonSerializer.Deserialize<GreetingRequest>(request.Body);

            var greeting = await service.GreetAsync(requestContent.Name, cts.Token);

            // ❌ Manual JSON serialization
            var responseJson = JsonSerializer.Serialize(
                new GreetingResponse(greeting, DateTime.UtcNow)
            );

            return new APIGatewayProxyResponse
            {
                Body = responseJson,
                StatusCode = 200,
                Headers = new Dictionary<string, string> { ["Content-Type"] = "application/json" },
            };
        },
        new DefaultLambdaJsonSerializer()
    )
    .Build()
    .RunAsync();
// ✅ Familiar .NET Core builder pattern
var builder = LambdaApplication.CreateBuilder();

builder.Services.AddScoped<IGreetingService, GreetingService>();

await using var lambda = builder.Build();

lambda.MapHandler(
    async (
        // ✅ Automatic envelope deserialization with strong typing
        [Event] ApiGatewayRequestEnvelope<GreetingRequest> request,
        // ✅ Automatic DI injection - proper scoped lifetime per invocation
        IGreetingService service,
        // ✅ Automatic cancellation token - framework manages timeout
        CancellationToken cancellationToken
    ) =>
    {
        var greeting = await service.GreetAsync(request.BodyContent.Name, cancellationToken);

        // ✅ Type-safe response - automatic JSON serialization
        return new ApiGatewayResponseEnvelope<GreetingResponse>
        {
            BodyContent = new GreetingResponse(greeting, DateTime.UtcNow),
            StatusCode = 200,
            Headers = new Dictionary<string, string> { ["Content-Type"] = "application/json" },
        };
    }
);

await lambda.RunAsync();

Key Features

.NET Hosting Patterns

Use middleware, the builder pattern, and dependency injection just like ASP.NET Core—with proper scoped lifetime management per invocation.

Learn about DI

Lifecycle Management

Run OnInit/OnShutdown hooks alongside your handler pipeline to warm resources, clear Lambda log formatting, and flush telemetry with host-managed cancellation tokens.

Lifecycle management

Source-Generated Handlers

Compile-time interception validates handler signatures, injects dependencies, and avoids reflection.

Handler registration

AOT Friendly

Source generation plus System.Text.Json contexts keep handlers ready for Native AOT publishing.

Advanced topics (Coming Soon)

Built-in Observability

OpenTelemetry integration emits traces and metrics without bolting on custom shims.

OpenTelemetry setup

Flexible Handler Registration

Map strongly typed handlers to envelopes or raw events with compile-time validation.

Handler registration

Minimal Runtime Overhead

Small abstraction surface area keeps CPU and memory usage predictable inside Lambda’s sandbox.

Advanced topics (Coming Soon)


Quick Start

Install the NuGet package:

dotnet add package AwsLambda.Host

Create your first Lambda handler:

using AwsLambda.Host.Builder;

var builder = LambdaApplication.CreateBuilder();
var lambda = builder.Build();

lambda.MapHandler(([Event] string name) => $"Hello {name}!");

await lambda.RunAsync();

Next Steps

Ready to dive deeper? Check out the Getting Started Guide for a complete tutorial, or explore the Examples to see real-world applications.


Packages

Core Packages

The core packages provide the fundamental hosting framework, abstractions, and observability support for building AWS Lambda functions.

Package Description NuGet Downloads
AwsLambda.Host Core hosting framework with middleware and DI NuGet Downloads
AwsLambda.Host.Abstractions Core interfaces and contracts NuGet Downloads
AwsLambda.Host.OpenTelemetry Distributed tracing and observability NuGet Downloads

Envelope Packages

Envelope packages provide type-safe handling of AWS Lambda event sources with automatic payload deserialization.

What are Envelopes?

Envelopes wrap AWS Lambda events with strongly-typed payload handling, giving you compile-time type safety and automatic deserialization of message bodies from SQS, SNS, Kinesis, and other event sources.

Learn more about envelopes

Package Description NuGet Downloads
AwsLambda.Host.Envelopes.Sqs Simple Queue Service events with typed message bodies NuGet Downloads
AwsLambda.Host.Envelopes.Sns Simple Notification Service messages NuGet Downloads
AwsLambda.Host.Envelopes.ApiGateway REST, HTTP, and WebSocket APIs NuGet Downloads
AwsLambda.Host.Envelopes.Kinesis Data Streams with typed records NuGet Downloads
AwsLambda.Host.Envelopes.KinesisFirehose Data transformation NuGet Downloads
AwsLambda.Host.Envelopes.Kafka MSK and self-managed Kafka NuGet Downloads
AwsLambda.Host.Envelopes.CloudWatchLogs Log subscriptions NuGet Downloads
AwsLambda.Host.Envelopes.Alb Application Load Balancer requests NuGet Downloads

Browse all envelope packages


Examples & Use Cases

Explore the repository’s examples/ folder and the docs’ Examples page (content coming soon) for end-to-end Lambda samples that wire up middleware, envelopes, and DI.

Examples (Coming Soon)


Community & Resources

Get Involved

Documentation

  • Getting Started – Installation and first Lambda tutorial.
  • Guides – In-depth docs on DI, middleware, lifecycle, configuration, and more.
  • Features – Envelopes, OpenTelemetry integration, and other add-ons.
  • Advanced Topics – Coming soon: AOT, source generators, performance tuning.

Support


Ready to modernize your Lambda development? Get started now