feat(host): add ILambdaLifecycleContext for lifecycle handlers#252
Merged
j-d-ha merged 27 commits intoDec 17, 2025
Merged
Conversation
…fetime - Introduced `LifetimeStopwatch` class to monitor elapsed time since application start. - Registered `LifetimeStopwatch` as a singleton in `LambdaApplicationBuilder`.
…bda lifecycle management - Introduced `ILambdaLifecycleContext` to encapsulate Lambda lifecycle event information such as initialization and shutdown. - Added properties like `CancellationToken`, `ElapsedTime`, `FunctionName`, `Region`, and other environment-specific details. - Intended to provide shared context for Lambda handlers.
- Added `LambdaLifecycleContext` class implementing `ILambdaLifecycleContext` for shared lifecycle context. - Introduced `LambdaLifecycleContextFactory` for creating `LambdaLifecycleContext` instances. - Updated `LambdaLifecycleContext` to include core Lambda environment details and integrate with DI. - Includes disposal logic to properly manage resources like `IServiceScope`.
- Added tests for `LambdaLifecycleContextFactory` to verify factory behavior and property resolution. - Added tests for `LambdaLifecycleContext` to confirm lazy initialization, property access, and resource disposal. - Validated configuration-based property initialization for Lambda environment variables. - Ensured context reusability and correctness across multiple calls.
…ycle context support - Replaced `LambdaInitDelegate` with `LambdaInitDelegate2` to incorporate `ILambdaLifecycleContext`. - Added `ILambdaLifecycleContextFactory` and `ConcurrentDictionary` for init handler shared state. - Updated `DefaultLambdaOnInitBuilderFactory` and `LambdaOnInitBuilder` to support the new context. - Removed obsolete `OnInitClearLambdaOutputFormatting` method for cleanup and modernization. - Enhanced init handler building logic with context-aware execution.
…matting - Renamed `ParameterSource.Context` to `ParameterSource.HostContext` for improved clarity. - Added new `ParameterSource.LifecycleContext` and support for `ILambdaLifecycleContext`. - Introduced `OutputFormattingLambdaApplicationExtensions.OnInitClearLambdaOutputFormatting` for custom formatting. - Updated generators and handlers to improve usage of `HostContext` and `LifecycleContext`. - Enhanced DI for services, ensuring proper keyed and optional service resolution. - Improved error handling and timeout behavior during `OnInit` execution. - Updated `LifetimeStopwatch` to initialize automatically with application start.
- Replaced `BuildHandlerSignature` with a new `BuildHandlerCastCall` method for improved clarity. - Updated `GenericHandler.scriban` to adapt to the new handler cast generation process. - Added a new `Cast<T>` helper method for safer and more explicit casting of delegate handlers. - Enhanced `BuildHandlerCastCall` to generate handler cast calls with detailed parameter and type info.
- Updated `OnInit` lambda argument to allow `IService? y` defaulting to `null` in unit tests.
…cycleContext` - Updated `OnInit` handler methods to replace `IServiceProvider` with `ILambdaLifecycleContext` parameter. - Updated `GenericHandler.scriban` to leverage lifecycle context for service resolution. - Introduced `Cast<T>` helper for safer and more explicit delegate casting across handlers. - Enhanced generated code to improve readability and maintainability by abstracting casting logic. - Adjusted unit tests to align with new `ILambdaLifecycleContext` usage and verify correctness.
…leContext` - Replaced `IServiceProvider` and `CancellationToken` parameters in `LambdaInitDelegate` with `ILambdaLifecycleContext`. - Simplified `LambdaInitDelegate` definition for improved usage consistency during the Function Init phase.
…nitDelegate` - Standardized usage of `LambdaInitDelegate` across initialization handlers. - Updated `ILambdaOnInitBuilder`, `LambdaOnInitBuilder`, and `LambdaApplication` implementation. - Simplified init handler logic for consistency and easier maintenance.
…ecycle services - Added `ILifetimeStopwatch` interface to abstract lifetime tracking functionality. - Updated `LifetimeStopwatch` to implement `ILifetimeStopwatch` for consistency and extensibility. - Replaced direct `LifetimeStopwatch` references with `ILifetimeStopwatch` in lifecycle services and factories. - Registered `ILifetimeStopwatch` as a singleton in relevant DI configurations. - Refactored test cases to align with the interface abstraction and validate the updated behavior.
…ApplicationBuilder` - Replaced manual host configuration with `LambdaApplicationBuilder` for cleaner test setups. - Updated related test files to utilize `LambdaApplicationBuilder` for creating hosts.
…eContext` and shared state - Updated `LambdaShutdownDelegate` to use `ILambdaLifecycleContext`, replacing `IServiceProvider` and `CancellationToken`. - Added `Properties` dictionary to `ILambdaOnShutdownBuilder` for shared state between handlers. - Unified `Properties` documentation between `ILambdaOnInitBuilder` and `ILambdaOnShutdownBuilder`.
…ogging and handler simplicity - Replaced `Console.WriteLine` with `ILogger` for better logging flexibility in `OnInit`. - Simplified `OnInit` handler signature, removing `IServiceCollection` from unused parameters. - Refactored `OnShutdown` to streamline the handler and remove unnecessary parameters.
…hared properties support - Added `ILambdaLifecycleContextFactory` to `LambdaOnShutdownBuilder` for creating lifecycle contexts. - Integrated `Properties` dictionary to enable shared state management between shutdown handlers. - Updated `LambdaShutdownDelegate` to use lifecycle context for improved consistency with `OnInit`. - Modified `DefaultLambdaOnShutdownBuilderFactory` to support context factory injection.
- Refactored `OnShutdown` handlers to simplify parameter usage by removing unused lambda arguments. - Added `MinimalLambda.SourceGenerators` as an analyzer and updated project references for extended functionality.
…ILambdaLifecycleContext` - Replaced `IServiceProvider` and `CancellationToken` with `ILambdaLifecycleContext` in `OnShutdown`. - Streamlined syntax matching for improved consistency and maintainability.
- Simplified test setups by removing redundant `IServiceProvider` and `IServiceScopeFactory` parameters. - Updated `LambdaShutdownDelegate` usage to align with recent changes, replacing unused lambda arguments. - Converted constructors and Fact-based test methods to enhanced Theory-based design for improved flexibility.
…ctory tests - Updated `DefaultLambdaOnShutdownBuilderFactoryTests` to include `ILambdaLifecycleContextFactory`. - Added validation for null `ILambdaLifecycleContextFactory` in test cases. - Refactored test setups to accommodate the new context factory parameter in the factory constructor.
…down tests - Removed unused lambda arguments in `LambdaShutdownDelegate` across test cases. - Updated test cases for improved readability and reduced redundancy in lambda signatures.
…legate` in tests - Simplified `LambdaShutdownDelegate` usage by removing unused lambda arguments across test cases. - Updated test cases to improve readability and align with streamlined delegate signatures.
…leContext` in tests - Updated shutdown handler tests to use `ILambdaLifecycleContext` instead of `IServiceProvider`. - Refactored mocked contexts and removed direct `CancellationToken` assignments from test cases. - Improved consistency with recent changes to `LambdaShutdownDelegate`.
- Replaced `IServiceProvider` and `CancellationToken` usage with `ILambdaLifecycleContext` in test cases. - Simplified lambda signature in shutdown handler to improve consistency with recent changes.
…plates - Removed `// Location: ...` comments from `GenericHandler.scriban` and `MapHandler.scriban`. - Simplified template files by eliminating unnecessary inline documentation.
…down builders - Integrated `Properties` dictionary into `ILambdaOnInitBuilder` and `ILambdaOnShutdownBuilder`. - Enabled propagation of shared properties between lifecycle handlers during Init and Shutdown.
- Updated lifecycle management guide to include `ILambdaLifecycleContext` usage and DI patterns. - Added examples for direct DI, AWS metadata access, state sharing, and keyed services in OnInit handlers. - Enhanced dependency injection guide with source-generated DI support for OnInit and OnShutdown. - Expanded core concepts with lifecycle context access patterns and practical usage scenarios.
j-d-ha
enabled auto-merge (squash)
December 17, 2025 01:22
|
j-d-ha
deleted the
feature/#236-add-ILambdaOnInitContext-for-OnInit-handlers
branch
December 17, 2025 01:23
Codecov Report❌ Patch coverage is @@ Coverage Diff @@
## main #252 +/- ##
==========================================
+ Coverage 88.23% 88.37% +0.13%
==========================================
Files 127 130 +3
Lines 2993 3115 +122
Branches 337 344 +7
==========================================
+ Hits 2641 2753 +112
- Misses 219 229 +10
Partials 133 133
... and 2 files with indirect coverage changes Continue to review full report in Codecov by Sentry.
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



🚀 Pull Request
📋 Summary
This PR introduces
ILambdaLifecycleContextto provide rich context and dependency injection capabilities for OnInit and OnShutdown lifecycle handlers. This replaces the previous(IServiceProvider, CancellationToken)delegate pattern with a more extensible, source-generated DI approach that mirrors the invocation handler pattern.Key Changes
1. New
ILambdaLifecycleContextInterfacePropertiesdictionary for sharing state between handlersServiceProviderandCancellationTokenMinimalLambda.Abstractionsfor broad accessibility2. Updated Handler Signatures
3. Source-Generated Dependency Injection
IServiceProviderresolution[FromKeyedServices("key")]attribute4. Comprehensive Documentation
ILambdaLifecycleContextusage patterns5. Extensive Test Coverage
ILambdaLifecycleContextand factory✅ Checklist
🧪 Related Issues or PRs
Closes #236
💬 Notes for Reviewers
Breaking Changes
This is a breaking change for existing OnInit/OnShutdown handlers:
(IServiceProvider, CancellationToken)to source-generated DIservices.GetRequiredService<T>()with direct parameter injectionKey Files to Review
Core Implementation:
src/MinimalLambda.Abstractions/Core/ILambdaLifecycleContext.cs- New interface definitionsrc/MinimalLambda/Core/Context/LambdaLifecycleContext.cs- Implementation with AWS env var readingsrc/MinimalLambda/Core/Context/LambdaLifecycleContextFactory.cs- Factory for creating contextsBuilder Updates:
src/MinimalLambda/Builder/LambdaOnInitBuilder.cs- Updated to use context factorysrc/MinimalLambda/Builder/LambdaOnShutdownBuilder.cs- Updated to use context factoryPropertiesdictionary for state sharingSource Generators:
src/MinimalLambda.SourceGenerators/SyntaxProviders/OnInitSyntaxProvider.cssrc/MinimalLambda.SourceGenerators/SyntaxProviders/OnShutdownSyntaxProvider.csILambdaLifecycleContextand new parameter sourcesDocumentation:
docs/guides/lifecycle-management.md- Comprehensive guide with examplesdocs/guides/dependency-injection.md- DI patterns for lifecycle handlersdocs/getting-started/core-concepts.md- Introductory overviewAWS Environment Properties
All AWS environment metadata is read from standard Lambda environment variables:
Properties Dictionary
The
Propertiesdictionary enables:ILambdaHostContext.PropertiesConcurrentDictionarybackingMigration Path
Existing code using old pattern:
Migrates to:
For advanced scenarios needing AWS metadata: