using Amazon.Lambda.AspNetCoreServer.Hosting;
using Amazon.Lambda.AspNetCoreServer.Internal;
using Amazon.Lambda.AspNetCoreServer.Hosting.Internal;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
///
/// Enum for the possible event sources that will send HTTP request into the ASP.NET Core Lambda function.
///
public enum LambdaEventSource
{
///
/// API Gateway REST API
///
RestApi,
///
/// API Gateway HTTP API
///
HttpApi,
///
/// ELB Application Load Balancer
///
ApplicationLoadBalancer
}
///
/// Extension methods to IServiceCollection.
///
public static class ServiceCollectionExtensions
{
///
/// Add the ability to run the ASP.NET Core Lambda function in AWS Lambda. If the project is not running in Lambda
/// this method will do nothing allowing the normal Kestrel webserver to host the application.
///
///
///
///
public static IServiceCollection AddAWSLambdaHosting(this IServiceCollection services, LambdaEventSource eventSource)
{
// Not running in Lambda so exit and let Kestrel be the web server
return services.AddAWSLambdaHosting(eventSource, (Action?)null);
}
///
/// Add the ability to run the ASP.NET Core Lambda function in AWS Lambda. If the project is not running in Lambda
/// this method will do nothing allowing the normal Kestrel webserver to host the application.
///
///
///
///
///
public static IServiceCollection AddAWSLambdaHosting(this IServiceCollection services, LambdaEventSource eventSource, Action? configure = null)
{
// Not running in Lambda so exit and let Kestrel be the web server
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME")))
return services;
var hostingOptions = new HostingOptions();
if (configure != null)
configure.Invoke(hostingOptions);
services.TryAddSingleton(hostingOptions.Serializer ?? new DefaultLambdaJsonSerializer());
var serverType = eventSource switch
{
LambdaEventSource.HttpApi => typeof(APIGatewayHttpApiV2LambdaRuntimeSupportServer),
LambdaEventSource.RestApi => typeof(APIGatewayRestApiLambdaRuntimeSupportServer),
LambdaEventSource.ApplicationLoadBalancer => typeof(ApplicationLoadBalancerLambdaRuntimeSupportServer),
_ => throw new ArgumentException($"Event source type {eventSource} unknown")
};
Utilities.EnsureLambdaServerRegistered(services, serverType);
return services;
}
}
}