diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md
index ffb739ddf..32ba97ef6 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md
@@ -28,3 +28,4 @@ AWSLambda0142 | AWSLambdaCSharpGenerator | Error | Invalid DurableExecution meth
AWSLambda0143 | AWSLambdaCSharpGenerator | Info | DurableExecution function with explicit Role needs checkpoint permissions
AWSLambda0144 | AWSLambdaCSharpGenerator | Error | Invalid DurableExecutionAttribute
AWSLambda0145 | AWSLambdaCSharpGenerator | Warning | Durable execution envelope types not registered with JsonSerializerContext
+AWSLambda0146 | AWSLambdaCSharpGenerator | Error | Invalid BuildServiceProvider method
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs
index cc40ce60a..0a64abd43 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs
@@ -330,5 +330,12 @@ public static class DiagnosticDescriptors
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
+
+ public static readonly DiagnosticDescriptor InvalidBuildServiceProviderMethod = new DiagnosticDescriptor(id: "AWSLambda0146",
+ title: "Invalid BuildServiceProvider method",
+ messageFormat: "The BuildServiceProvider method on the Startup class must take a single IServiceCollection parameter and return IServiceProvider or a type implementing it: {0}",
+ category: "AWSLambdaCSharpGenerator",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
}
}
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Generator.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Generator.cs
index 2b92d958c..24a2b5a32 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Generator.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Generator.cs
@@ -138,15 +138,26 @@ public void Execute(GeneratorExecutionContext context)
var configureHostBuilderMethodSymbol = semanticModelProvider.GetConfigureHostBuilderMethodModel(receiver.StartupClasses.FirstOrDefault());
var configureServicesMethodSymbol = semanticModelProvider.GetConfigureServicesMethodModel(receiver.StartupClasses.FirstOrDefault());
var configureMethodSymbol = configureServicesMethodSymbol;
+ var buildServiceProviderMethodSymbol = semanticModelProvider.GetBuildServiceProviderMethodModel(receiver.StartupClasses.FirstOrDefault());
if (configureServicesMethodSymbol != null && configureHostBuilderMethodSymbol != null)
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MultipleConfigureMethodsNotAllowed, configureServicesMethodSymbol.Locations.FirstOrDefault(), configureServicesMethodSymbol.Name, configureHostBuilderMethodSymbol.Name));
}
+ if (buildServiceProviderMethodSymbol != null && !semanticModelProvider.IsValidBuildServiceProviderMethod(buildServiceProviderMethodSymbol))
+ {
+ diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.InvalidBuildServiceProviderMethod, buildServiceProviderMethodSymbol.Locations.FirstOrDefault(), buildServiceProviderMethodSymbol.Name));
+ buildServiceProviderMethodSymbol = null;
+ }
+
if (configureHostBuilderMethodSymbol != null)
{
configureMethodSymbol = configureHostBuilderMethodSymbol;
+ // The BuildServiceProvider hook only applies to the ConfigureServices path.
+ // With a host builder the container is configured through ConfigureHostBuilder
+ // and the generated code uses host.Services, so the hook is ignored.
+ buildServiceProviderMethodSymbol = null;
}
// Check for methods that have secondary attributes (HttpApi, RestApi, HttpApiAuthorizer, etc.)
@@ -171,7 +182,7 @@ public void Execute(GeneratorExecutionContext context)
var lambdaMethodSymbol = semanticModelProvider.GetMethodSemanticModel(lambdaMethodDeclarationSyntax);
var lambdaMethodLocation = lambdaMethodDeclarationSyntax.GetLocation();
- var lambdaFunctionModel = LambdaFunctionModelBuilder.BuildAndValidate(lambdaMethodSymbol, lambdaMethodLocation, configureMethodSymbol, context, isExecutable, defaultRuntime, diagnosticReporter);
+ var lambdaFunctionModel = LambdaFunctionModelBuilder.BuildAndValidate(lambdaMethodSymbol, lambdaMethodLocation, configureMethodSymbol, buildServiceProviderMethodSymbol, context, isExecutable, defaultRuntime, diagnosticReporter);
if (!lambdaFunctionModel.IsValid)
{
// If the model is not valid then skip it from further processing
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModelBuilder.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModelBuilder.cs
index db7fa4d67..af5a130e2 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModelBuilder.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModelBuilder.cs
@@ -14,7 +14,7 @@ namespace Amazon.Lambda.Annotations.SourceGenerator.Models
///
public static class LambdaFunctionModelBuilder
{
- public static LambdaFunctionModel BuildAndValidate(IMethodSymbol lambdaMethodSymbol, Location LambdamethodLocation, IMethodSymbol configureMethodSymbol, GeneratorExecutionContext context, bool isExecutable, string runtime, DiagnosticReporter diagnosticReporter)
+ public static LambdaFunctionModel BuildAndValidate(IMethodSymbol lambdaMethodSymbol, Location LambdamethodLocation, IMethodSymbol configureMethodSymbol, IMethodSymbol buildServiceProviderMethodSymbol, GeneratorExecutionContext context, bool isExecutable, string runtime, DiagnosticReporter diagnosticReporter)
{
// We need to check for the necessary dependencies before attempting to build the LambdaFunctionModel otherwise the generator blows up with unknown exceptions.
if (!LambdaFunctionValidator.ValidateDependencies(context, lambdaMethodSymbol, LambdamethodLocation, diagnosticReporter))
@@ -22,14 +22,14 @@ public static LambdaFunctionModel BuildAndValidate(IMethodSymbol lambdaMethodSym
return new LambdaFunctionModel() { IsValid = false };
}
- var lambdaFunctionModel = Build(lambdaMethodSymbol, configureMethodSymbol, context, isExecutable, runtime);
+ var lambdaFunctionModel = Build(lambdaMethodSymbol, configureMethodSymbol, buildServiceProviderMethodSymbol, context, isExecutable, runtime);
lambdaFunctionModel.IsValid = LambdaFunctionValidator.ValidateFunction(context, lambdaMethodSymbol, LambdamethodLocation, lambdaFunctionModel, diagnosticReporter);
return lambdaFunctionModel;
}
- private static LambdaFunctionModel Build(IMethodSymbol lambdaMethodSymbol, IMethodSymbol configureMethodSymbol, GeneratorExecutionContext context, bool isExecutable, string runtime)
+ private static LambdaFunctionModel Build(IMethodSymbol lambdaMethodSymbol, IMethodSymbol configureMethodSymbol, IMethodSymbol buildServiceProviderMethodSymbol, GeneratorExecutionContext context, bool isExecutable, string runtime)
{
- var lambdaMethod = LambdaMethodModelBuilder.Build(lambdaMethodSymbol, configureMethodSymbol, context);
+ var lambdaMethod = LambdaMethodModelBuilder.Build(lambdaMethodSymbol, configureMethodSymbol, buildServiceProviderMethodSymbol, context);
var generatedMethod = GeneratedMethodModelBuilder.Build(lambdaMethodSymbol, configureMethodSymbol, lambdaMethod, context);
var model = new LambdaFunctionModel()
{
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModel.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModel.cs
index 601e4d86e..e48d8e2ef 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModel.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModel.cs
@@ -152,6 +152,14 @@ public bool ReturnsVoidTaskOrSqsBatchResponse
public bool UsingHostBuilderForDependencyInjection { get; set; }
+ ///
+ /// Returns true if the Startup class defines a BuildServiceProvider method that
+ /// the generated code should use to create the
+ /// instead of the default .
+ /// This allows using an alternate IoC container, for example Autofac.
+ ///
+ public bool UsingCustomServiceProvider { get; set; }
+
///
/// Gets or sets the namespace for the nearest enclosing namespace. Returns null if the
/// symbol isn't contained in a namespace.
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModelBuilder.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModelBuilder.cs
index 5c1347b3a..c0c1050af 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModelBuilder.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaMethodModelBuilder.cs
@@ -12,6 +12,7 @@ public static class LambdaMethodModelBuilder
{
public static LambdaMethodModel Build(IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
+ IMethodSymbol buildServiceProviderMethodSymbol,
GeneratorExecutionContext context)
{
var model = new LambdaMethodModel
@@ -28,6 +29,7 @@ public static LambdaMethodModel Build(IMethodSymbol lambdaMethodSymbol,
ContainingType = TypeModelBuilder.Build(lambdaMethodSymbol.ContainingType, context),
UsingDependencyInjection = configureMethodSymbol != null,
UsingHostBuilderForDependencyInjection = configureMethodSymbol != null && configureMethodSymbol.Name == "ConfigureHostBuilder",
+ UsingCustomServiceProvider = buildServiceProviderMethodSymbol != null,
Attributes = lambdaMethodSymbol.GetAttributes().Select(att => AttributeModelBuilder.Build(att, context)).ToList()
};
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/SemanticModelProvider.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/SemanticModelProvider.cs
index 84aeb2e68..4cf1a4044 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/SemanticModelProvider.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/SemanticModelProvider.cs
@@ -79,6 +79,75 @@ public IMethodSymbol GetConfigureHostBuilderMethodModel(ClassDeclarationSyntax s
return configureHostBuilderMethodSymbol;
}
+ ///
+ /// Returns the BuildServiceProvider method's semantic model in the LambdaStartup attributed class,
+ /// if the class defines one. The method is expected to take a single IServiceCollection parameter
+ /// and return an IServiceProvider, allowing an alternate IoC container to be used.
+ /// The signature is validated by the caller; this method returns the symbol even when the
+ /// signature does not match so an invalid definition can be reported.
+ /// If is null, returns null.
+ ///
+ /// LambdaStartup attributed class syntax
+ public IMethodSymbol GetBuildServiceProviderMethodModel(ClassDeclarationSyntax startupSyntax)
+ {
+ if (startupSyntax == null)
+ {
+ return null;
+ }
+
+ var classModel = _context.Compilation.GetSemanticModel(startupSyntax.SyntaxTree);
+
+ foreach (var member in startupSyntax.Members.Where(member => member.Kind() == SyntaxKind.MethodDeclaration))
+ {
+ var methodSyntax = (MethodDeclarationSyntax)member;
+ var methodSymbol = classModel.GetDeclaredSymbol(methodSyntax);
+ if (methodSymbol != null && methodSymbol.Name == "BuildServiceProvider")
+ {
+ return methodSymbol;
+ }
+ }
+
+ return null;
+ }
+
+ ///
+ /// Returns true if is a valid
+ /// BuildServiceProvider hook: a non-private method taking a single IServiceCollection
+ /// parameter and returning IServiceProvider or a type implementing it.
+ ///
+ public bool IsValidBuildServiceProviderMethod(IMethodSymbol buildServiceProviderMethodSymbol)
+ {
+ if (buildServiceProviderMethodSymbol == null)
+ {
+ return false;
+ }
+
+ if (buildServiceProviderMethodSymbol.DeclaredAccessibility == Accessibility.Private)
+ {
+ return false;
+ }
+
+ if (buildServiceProviderMethodSymbol.Parameters.Length != 1)
+ {
+ return false;
+ }
+
+ var iServiceCollectionSymbol = _context.Compilation.GetTypeByMetadataName("Microsoft.Extensions.DependencyInjection.IServiceCollection");
+ if (!buildServiceProviderMethodSymbol.Parameters[0].Type.Equals(iServiceCollectionSymbol, SymbolEqualityComparer.Default))
+ {
+ return false;
+ }
+
+ var iServiceProviderSymbol = _context.Compilation.GetTypeByMetadataName("System.IServiceProvider");
+ var returnType = buildServiceProviderMethodSymbol.ReturnType;
+ if (returnType.Equals(iServiceProviderSymbol, SymbolEqualityComparer.Default))
+ {
+ return true;
+ }
+
+ return returnType.AllInterfaces.Any(i => i.Equals(iServiceProviderSymbol, SymbolEqualityComparer.Default));
+ }
+
///
/// Returns semantic model of
///
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs
index 37d50c71b..4b96d3a43 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs
@@ -38,7 +38,7 @@ public virtual string TransformText()
#line default
#line hidden
- this.Write(" private readonly ServiceProvider serviceProvider;\r\n");
+ this.Write(" private readonly IServiceProvider serviceProvider;\r\n");
#line 12 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
@@ -149,11 +149,9 @@ public virtual string TransformText()
#line default
#line hidden
- this.Write(">();\r\n\r\n serviceProvider = hostBuilder.Services.BuildServiceProvider()" +
- ";\r\n\r\n host = hostBuilder.Build();\r\n host.RunAsync();\r\n\r\n " +
- " // Intentionally eagerly build ");
+ this.Write(">();\r\n\r\n host = hostBuilder.Build();\r\n\r\n // The service provider comes from the host so a custom container configured\r\n // in Startup.ConfigureHostBuilder (via ConfigureContainer or UseServiceProviderFactory) is used.\r\n serviceProvider = host.Services;\r\n host.RunAsync();\r\n\r\n // Intentionally eagerly build ");
- #line 59 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 61 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
@@ -161,14 +159,14 @@ public virtual string TransformText()
this.Write(" and its dependencies.\r\n // This causes time spent in the Constructor " +
"to appear on INIT_REPORTs\r\n _ = serviceProvider.GetRequiredService<");
- #line 61 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 63 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n");
- #line 62 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 64 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
else
@@ -183,30 +181,54 @@ public virtual string TransformText()
// To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method.
services.AddSingleton<");
- #line 71 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 73 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n services.AddSingleton<");
- #line 72 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 74 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.SerializerInfo.SerializerName));
#line default
#line hidden
this.Write(">();\r\n\r\n var startup = new ");
- #line 74 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 76 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.StartupType.FullName));
#line default
#line hidden
- this.Write("();\r\n startup.ConfigureServices(services);\r\n serviceProvide" +
- "r = services.BuildServiceProvider();\r\n\r\n // Intentionally eagerly bui" +
- "ld ");
+ this.Write("();\r\n startup.ConfigureServices(services);\r\n");
+
+ #line 79 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ if (_model.LambdaMethod.UsingCustomServiceProvider)
+ {
+
+
+ #line default
+ #line hidden
+ this.Write(" serviceProvider = startup.BuildServiceProvider(services);\r\n");
+
+ #line 84 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ }
+ else
+ {
+
+
+ #line default
+ #line hidden
+ this.Write(" serviceProvider = services.BuildServiceProvider();\r\n");
+
+ #line 90 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ }
+
+ #line default
+ #line hidden
+ this.Write("\r\n // Intentionally eagerly build ");
- #line 78 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 93 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
@@ -214,14 +236,14 @@ public virtual string TransformText()
this.Write(" and its dependencies.\r\n // This causes time spent in the Constructor " +
"to appear on INIT_REPORTs\r\n _ = serviceProvider.GetRequiredService<");
- #line 80 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 95 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n");
- #line 81 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 96 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
}
@@ -233,28 +255,28 @@ public virtual string TransformText()
#line hidden
this.Write(" ");
- #line 87 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 102 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(" = new ");
- #line 87 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 102 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write("();\r\n serializer = new ");
- #line 88 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 103 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.SerializerInfo.SerializerName));
#line default
#line hidden
this.Write("();\r\n");
- #line 89 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
+ #line 104 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt
index 35a1f2c59..caeca2a38 100644
--- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt
+++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt
@@ -8,7 +8,7 @@
if (_model.LambdaMethod.UsingDependencyInjection)
{
#>
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
<#
if (_model.LambdaMethod.UsingHostBuilderForDependencyInjection)
{
@@ -51,9 +51,11 @@
hostBuilder.Services.AddSingleton<<#= _model.LambdaMethod.ContainingType.Name #>>();
hostBuilder.Services.AddSingleton<<#= _model.SerializerInfo.SerializerName #>>();
- serviceProvider = hostBuilder.Services.BuildServiceProvider();
-
host = hostBuilder.Build();
+
+ // The service provider comes from the host so a custom container configured
+ // in Startup.ConfigureHostBuilder (via ConfigureContainer or UseServiceProviderFactory) is used.
+ serviceProvider = host.Services;
host.RunAsync();
// Intentionally eagerly build <#= _model.LambdaMethod.ContainingType.Name #> and its dependencies.
@@ -73,7 +75,20 @@
var startup = new <#= _model.StartupType.FullName #>();
startup.ConfigureServices(services);
+<#
+ if (_model.LambdaMethod.UsingCustomServiceProvider)
+ {
+#>
+ serviceProvider = startup.BuildServiceProvider(services);
+<#
+ }
+ else
+ {
+#>
serviceProvider = services.BuildServiceProvider();
+<#
+ }
+#>
// Intentionally eagerly build <#= _model.LambdaMethod.ContainingType.Name #> and its dependencies.
// This causes time spent in the Constructor to appear on INIT_REPORTs
diff --git a/Libraries/src/Amazon.Lambda.Annotations/README.md b/Libraries/src/Amazon.Lambda.Annotations/README.md
index 56cb7bbd7..30b653ab0 100644
--- a/Libraries/src/Amazon.Lambda.Annotations/README.md
+++ b/Libraries/src/Amazon.Lambda.Annotations/README.md
@@ -213,6 +213,40 @@ public class Startup
}
```
+### Using an alternate IoC container
+
+By default the generated code builds the service provider from the `IServiceCollection` with
+`services.BuildServiceProvider()`. If you use a different container (for example Autofac or
+Simple Injector), add a `BuildServiceProvider` method to your startup class that takes the
+`IServiceCollection` and returns an `IServiceProvider` (or a type implementing it). The generated
+code will call it instead of `services.BuildServiceProvider()`.
+
+```csharp
+[LambdaStartup]
+public class Startup
+{
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddAWSService();
+ services.AddScoped();
+ }
+
+ public IServiceProvider BuildServiceProvider(IServiceCollection services)
+ {
+ var builder = new ContainerBuilder();
+ builder.Populate(services);
+ builder.RegisterType().As();
+ return new AutofacServiceProvider(builder.Build());
+ }
+}
+```
+
+The method must take exactly one `IServiceCollection` parameter and return `IServiceProvider` or a
+type implementing it. Otherwise the generator reports an error (AWSLambda0146). When using the
+`ConfigureHostBuilder` path above there is no need for this method — configure the container on the
+host builder with `ConfigureContainer` or `UseServiceProviderFactory` instead, and the generated
+code uses `host.Services`.
+
Example function using DI:
```csharp
public class Functions
@@ -516,7 +550,7 @@ informational purposes, as a user of the Lambda Annotations framework this code
```csharp
public class Functions_Add_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
public Functions_Add_Generated()
{
@@ -528,9 +562,11 @@ public class Functions_Add_Generated
// To use a different lifetime, specify the lifetime in Startup.ConfigureHostBuilder() method.
hostBuilder.Services.AddSingleton();
- serviceProvider = hostBuilder.Services.BuildServiceProvider();
-
host = hostBuilder.Build();
+
+ // The service provider comes from the host so a custom container configured
+ // in Startup.ConfigureHostBuilder (via ConfigureContainer or UseServiceProviderFactory) is used.
+ serviceProvider = host.Services;
host.RunAsync();
}
@@ -734,7 +770,7 @@ informational purposes, as a user of the Lambda Annotations framework this code
```csharp
public class Functions_Resize_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
public Functions_Resize_Generated()
{
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Amazon.Lambda.Annotations.SourceGenerators.Tests.csproj b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Amazon.Lambda.Annotations.SourceGenerators.Tests.csproj
index 1cd1319a3..612e4bf51 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Amazon.Lambda.Annotations.SourceGenerators.Tests.csproj
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Amazon.Lambda.Annotations.SourceGenerators.Tests.csproj
@@ -49,6 +49,15 @@
+
+ TestCustomServiceProviderApp\%(RecursiveDir)/%(FileName)%(Extension)
+ Always
+
+
+
+
+
+
TestServerlessApp.NET8\%(RecursiveDir)/%(FileName)%(Extension)
Always
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/CustomServiceProviderFunctions_Add_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/CustomServiceProviderFunctions_Add_Generated.g.cs
new file mode 100644
index 000000000..f1fdec4ae
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/CustomServiceProviderFunctions_Add_Generated.g.cs
@@ -0,0 +1,135 @@
+//
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading.Tasks;
+using System.IO;
+using Microsoft.Extensions.DependencyInjection;
+using Amazon.Lambda.Core;
+
+namespace TestCustomServiceProviderApp
+{
+ ///
+ /// The generated Lambda function handler for .
+ ///
+ public class CustomServiceProviderFunctions_Add_Generated
+ {
+ private readonly IServiceProvider serviceProvider;
+
+ ///
+ /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
+ /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
+ /// region the Lambda function is executed in.
+ ///
+ public CustomServiceProviderFunctions_Add_Generated()
+ {
+ SetExecutionEnvironment();
+ var services = new ServiceCollection();
+
+ // By default, Lambda function class is added to the service container using the singleton lifetime
+ // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method.
+ services.AddSingleton();
+ services.AddSingleton();
+
+ var startup = new TestCustomServiceProviderApp.Startup();
+ startup.ConfigureServices(services);
+ serviceProvider = startup.BuildServiceProvider(services);
+
+ // Intentionally eagerly build CustomServiceProviderFunctions and its dependencies.
+ // This causes time spent in the Constructor to appear on INIT_REPORTs
+ _ = serviceProvider.GetRequiredService();
+ }
+
+ ///
+ /// The generated Lambda function handler for
+ ///
+ /// The API Gateway request object that will be processed by the Lambda function handler.
+ /// The ILambdaContext that provides methods for logging and describing the Lambda environment.
+ /// Result of the Lambda function execution
+ public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse Add(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
+ {
+ // Create a scope for every request,
+ // this allows creating scoped dependencies without creating a scope manually.
+ using var scope = serviceProvider.CreateScope();
+ var customServiceProviderFunctions = scope.ServiceProvider.GetRequiredService();
+ var serializer = scope.ServiceProvider.GetRequiredService();
+
+ var validationErrors = new List();
+
+ var x = default(int);
+ if (__request__.PathParameters?.ContainsKey("x") == true)
+ {
+ try
+ {
+ x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int));
+ }
+ catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
+ {
+ validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}");
+ }
+ }
+
+ var y = default(int);
+ if (__request__.PathParameters?.ContainsKey("y") == true)
+ {
+ try
+ {
+ y = (int)Convert.ChangeType(__request__.PathParameters["y"], typeof(int));
+ }
+ catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
+ {
+ validationErrors.Add($"Value {__request__.PathParameters["y"]} at 'y' failed to satisfy constraint: {e.Message}");
+ }
+ }
+
+ // return 400 Bad Request if there exists a validation error
+ if (validationErrors.Any())
+ {
+ var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
+ {
+ Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
+ Headers = new Dictionary
+ {
+ {"Content-Type", "application/json"},
+ {"x-amzn-ErrorType", "ValidationException"}
+ },
+ StatusCode = 400
+ };
+ return errorResult;
+ }
+
+ var response = customServiceProviderFunctions.Add(x, y, __context__);
+
+ var body = response.ToString();
+
+ return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
+ {
+ Body = body,
+ Headers = new Dictionary
+ {
+ {"Content-Type", "application/json"}
+ },
+ StatusCode = 200
+ };
+ }
+
+ private static void SetExecutionEnvironment()
+ {
+ const string envName = "AWS_EXECUTION_ENV";
+
+ var envValue = new StringBuilder();
+
+ // If there is an existing execution environment variable add the annotations package as a suffix.
+ if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
+ {
+ envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
+ }
+
+ envValue.Append("lib/amazon-lambda-annotations#{ANNOTATIONS_ASSEMBLY_VERSION}");
+
+ Environment.SetEnvironmentVariable(envName, envValue.ToString());
+ }
+ }
+}
\ No newline at end of file
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToLower_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToLower_Generated.g.cs
index 63f65d269..746de83d6 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToLower_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToLower_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp.Sub1
///
public class FunctionsZipOutput_ToLower_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToUpper_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToUpper_Generated.g.cs
index fe23894f4..db6c44720 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToUpper_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/Functions_AsyncStartupToUpper_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp.Sub1
///
public class Functions_ToUpper_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHelloAsync_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHelloAsync_Generated.g.cs
index d4a9d4f89..e2fca42f8 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHelloAsync_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHelloAsync_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class Greeter_SayHelloAsync_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHello_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHello_Generated.g.cs
index ae7a7b4e3..95da8a9af 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHello_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/GreeterExecutable_SayHello_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class Greeter_SayHello_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/HostBuilderFunctions_Add_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/HostBuilderFunctions_Add_Generated.g.cs
index 9d79f4ad2..4feedac22 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/HostBuilderFunctions_Add_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/HostBuilderFunctions_Add_Generated.g.cs
@@ -17,7 +17,7 @@ namespace TestHostBuilderApp
///
public class HostBuilderFunctions_Add_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
private readonly IHost host;
///
@@ -36,9 +36,11 @@ public HostBuilderFunctions_Add_Generated()
hostBuilder.Services.AddSingleton();
hostBuilder.Services.AddSingleton();
- serviceProvider = hostBuilder.Services.BuildServiceProvider();
-
host = hostBuilder.Build();
+
+ // The service provider comes from the host so a custom container configured
+ // in Startup.ConfigureHostBuilder (via ConfigureContainer or UseServiceProviderFactory) is used.
+ serviceProvider = host.Services;
host.RunAsync();
// Intentionally eagerly build HostBuilderFunctions and its dependencies.
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/ServerlessTemplates/customServiceProvider.serverless.template b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/ServerlessTemplates/customServiceProvider.serverless.template
new file mode 100644
index 000000000..ed012b55c
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/ServerlessTemplates/customServiceProvider.serverless.template
@@ -0,0 +1,42 @@
+{
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Description": "This template is partially managed by Amazon.Lambda.Annotations (v{ANNOTATIONS_ASSEMBLY_VERSION}).",
+ "Resources": {
+ "TestCustomServiceProviderAppCustomServiceProviderFunctionsAddGenerated": {
+ "Type": "AWS::Serverless::Function",
+ "Metadata": {
+ "Tool": "Amazon.Lambda.Annotations",
+ "SyncedEvents": [
+ "RootGet"
+ ],
+ "SyncedEventProperties": {
+ "RootGet": [
+ "Path",
+ "Method"
+ ]
+ }
+ },
+ "Properties": {
+ "Runtime": "dotnet10",
+ "CodeUri": ".",
+ "MemorySize": 512,
+ "Timeout": 30,
+ "Policies": [
+ "AWSLambdaBasicExecutionRole"
+ ],
+ "PackageType": "Zip",
+ "Handler": "TestProject::TestCustomServiceProviderApp.CustomServiceProviderFunctions_Add_Generated::Add",
+ "Events": {
+ "RootGet": {
+ "Type": "HttpApi",
+ "Properties": {
+ "Path": "/add/{x}/{y}",
+ "Method": "GET"
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Add_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Add_Generated.g.cs
index 4b456256d..36dba6222 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Add_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Add_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Add_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_DivideAsync_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_DivideAsync_Generated.g.cs
index a61ad4216..9c31147aa 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_DivideAsync_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_DivideAsync_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_DivideAsync_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Multiply_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Multiply_Generated.g.cs
index 9e3cbab29..43b572ec0 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Multiply_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Multiply_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Multiply_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Pi_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Pi_Generated.g.cs
index c16b4ceb2..a64f92aef 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Pi_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Pi_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Pi_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Random_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Random_Generated.g.cs
index 0ba7fc780..d24ddc7d8 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Random_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Random_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Random_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Randoms_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Randoms_Generated.g.cs
index eca1f607a..af06a1901 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Randoms_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Randoms_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Randoms_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Subtract_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Subtract_Generated.g.cs
index 0c9429d01..ac9c346c2 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Subtract_Generated.g.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/SimpleCalculator_Subtract_Generated.g.cs
@@ -16,7 +16,7 @@ namespace TestServerlessApp
///
public class SimpleCalculator_Subtract_Generated
{
- private readonly ServiceProvider serviceProvider;
+ private readonly IServiceProvider serviceProvider;
///
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/SourceGeneratorTests.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/SourceGeneratorTests.cs
index 009c6643c..c05fae665 100644
--- a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/SourceGeneratorTests.cs
+++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/SourceGeneratorTests.cs
@@ -1849,6 +1849,96 @@ public async Task HostBuilder()
}.RunAsync();
}
+ [Fact]
+ public async Task CustomServiceProvider()
+ {
+ var expectedAddGenerated = await ReadSnapshotContent(Path.Combine("Snapshots", "CustomServiceProviderFunctions_Add_Generated.g.cs"));
+ var expectedTemplate = await ReadSnapshotContent(Path.Combine("Snapshots", "ServerlessTemplates", "customServiceProvider.serverless.template"));
+
+ await new VerifyCS.Test
+ {
+ TestState =
+ {
+ Sources =
+ {
+ (Path.Combine("TestCustomServiceProviderApp", "CustomServiceProviderFunctions.cs"), await File.ReadAllTextAsync(Path.Combine("TestCustomServiceProviderApp", "CustomServiceProviderFunctions.cs"))),
+ (Path.Combine("TestCustomServiceProviderApp", "Startup.cs"), await File.ReadAllTextAsync(Path.Combine("TestCustomServiceProviderApp", "Startup.cs"))),
+ (Path.Combine("TestCustomServiceProviderApp", "CustomServiceProvider.cs"), await File.ReadAllTextAsync(Path.Combine("TestCustomServiceProviderApp", "CustomServiceProvider.cs"))),
+ (Path.Combine("TestCustomServiceProviderApp", "CalculatorService", "ICalculatorService.cs"), await File.ReadAllTextAsync(Path.Combine("TestCustomServiceProviderApp", "CalculatorService", "ICalculatorService.cs"))),
+ (Path.Combine("TestCustomServiceProviderApp", "CalculatorService", "CalculatorService.cs"), await File.ReadAllTextAsync(Path.Combine("TestCustomServiceProviderApp", "CalculatorService", "CalculatorService.cs"))),
+
+ },
+ GeneratedSources =
+ {
+ (
+ typeof(SourceGenerator.Generator),
+ "CustomServiceProviderFunctions_Add_Generated.g.cs",
+ SourceText.From(expectedAddGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
+ ),
+
+ },
+ ExpectedDiagnostics =
+ {
+ new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("CustomServiceProviderFunctions_Add_Generated.g.cs", expectedAddGenerated),
+ new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestCustomServiceProviderApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplate),
+ }
+ }
+ }.RunAsync();
+ }
+
+ [Fact]
+ public async Task InvalidBuildServiceProviderSignature_ReportsError()
+ {
+ var source = @"
+using Amazon.Lambda.Annotations;
+using Amazon.Lambda.Core;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace MyApp
+{
+ [LambdaStartup]
+ public class Startup
+ {
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddSingleton();
+ }
+
+ public void BuildServiceProvider(IServiceCollection services)
+ {
+ }
+ }
+
+ public class Functions
+ {
+ }
+}";
+ var test = new VerifyCS.Test
+ {
+ TestState =
+ {
+ Sources =
+ {
+ ("Startup.cs", source),
+ (Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), await File.ReadAllTextAsync(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
+ (Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), await File.ReadAllTextAsync(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
+ },
+ ExpectedDiagnostics =
+ {
+ new DiagnosticResult("AWSLambda0146", DiagnosticSeverity.Error)
+ .WithSpan("Startup.cs", 16, 21, 16, 41)
+ .WithArguments("BuildServiceProvider"),
+ }
+ },
+ CompilerDiagnostics = CompilerDiagnostics.None
+ };
+ // Ignore the per-file codegen Info noise (AWSLambda0103) and the generated-source list
+ // so this test focuses on the invalid-signature diagnostic.
+ test.DisabledDiagnostics.Add("AWSLambda0103");
+ test.TestBehaviors |= TestBehaviors.SkipGeneratedSourcesCheck;
+ await test.RunAsync();
+ }
+
[Fact]
public async Task CustomAuthorizerRestTest()
{
diff --git a/Libraries/test/TestCustomServiceProviderApp/CalculatorService/CalculatorService.cs b/Libraries/test/TestCustomServiceProviderApp/CalculatorService/CalculatorService.cs
new file mode 100644
index 000000000..e412aec17
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/CalculatorService/CalculatorService.cs
@@ -0,0 +1,14 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+namespace TestCustomServiceProviderApp
+{
+ public class CalculatorService : ICalculatorService
+ {
+ ///
+ public int Add(int x, int y)
+ {
+ return x + y;
+ }
+ }
+}
diff --git a/Libraries/test/TestCustomServiceProviderApp/CalculatorService/ICalculatorService.cs b/Libraries/test/TestCustomServiceProviderApp/CalculatorService/ICalculatorService.cs
new file mode 100644
index 000000000..caf8dfaae
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/CalculatorService/ICalculatorService.cs
@@ -0,0 +1,19 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+namespace TestCustomServiceProviderApp
+{
+ ///
+ /// An interface for a service that implements the business logic of our Lambda functions
+ ///
+ public interface ICalculatorService
+ {
+ ///
+ /// Adds x and y together
+ ///
+ /// Addend
+ /// Addend
+ /// Sum of x and y
+ int Add(int x, int y);
+ }
+}
diff --git a/Libraries/test/TestCustomServiceProviderApp/CustomServiceProvider.cs b/Libraries/test/TestCustomServiceProviderApp/CustomServiceProvider.cs
new file mode 100644
index 000000000..24d2a6508
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/CustomServiceProvider.cs
@@ -0,0 +1,25 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System;
+
+namespace TestCustomServiceProviderApp;
+
+///
+/// A minimal that delegates to the default provider.
+/// It stands in for an alternate IoC container (for example Autofac) in the tests.
+///
+public class CustomServiceProvider : IServiceProvider
+{
+ private readonly IServiceProvider _inner;
+
+ public CustomServiceProvider(IServiceProvider inner)
+ {
+ _inner = inner;
+ }
+
+ public object GetService(Type serviceType)
+ {
+ return _inner.GetService(serviceType);
+ }
+}
diff --git a/Libraries/test/TestCustomServiceProviderApp/CustomServiceProviderFunctions.cs b/Libraries/test/TestCustomServiceProviderApp/CustomServiceProviderFunctions.cs
new file mode 100644
index 000000000..a8c0f84a4
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/CustomServiceProviderFunctions.cs
@@ -0,0 +1,28 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Amazon.Lambda.Core;
+using Amazon.Lambda.Annotations;
+using Amazon.Lambda.Annotations.APIGateway;
+
+[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
+
+namespace TestCustomServiceProviderApp;
+
+public class CustomServiceProviderFunctions
+{
+ private ICalculatorService _calculatorService;
+
+ public CustomServiceProviderFunctions(ICalculatorService calculatorService)
+ {
+ _calculatorService = calculatorService;
+ }
+
+ [LambdaFunction()]
+ [HttpApi(LambdaHttpMethod.Get, "/add/{x}/{y}")]
+ public int Add(int x, int y, ILambdaContext context)
+ {
+ var sum = _calculatorService.Add(x, y);
+ return sum;
+ }
+}
diff --git a/Libraries/test/TestCustomServiceProviderApp/Startup.cs b/Libraries/test/TestCustomServiceProviderApp/Startup.cs
new file mode 100644
index 000000000..5f5567f70
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/Startup.cs
@@ -0,0 +1,26 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Microsoft.Extensions.DependencyInjection;
+using System;
+
+namespace TestCustomServiceProviderApp;
+
+[Amazon.Lambda.Annotations.LambdaStartup]
+public class Startup
+{
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddSingleton(new CalculatorService());
+ }
+
+ ///
+ /// Builds the service provider used by the generated Lambda function handler.
+ /// Returning a custom here lets the function use
+ /// an alternate IoC container instead of the default Microsoft.Extensions.DependencyInjection one.
+ ///
+ public IServiceProvider BuildServiceProvider(IServiceCollection services)
+ {
+ return new CustomServiceProvider(services.BuildServiceProvider());
+ }
+}
diff --git a/Libraries/test/TestCustomServiceProviderApp/TestCustomServiceProviderApp.csproj b/Libraries/test/TestCustomServiceProviderApp/TestCustomServiceProviderApp.csproj
new file mode 100644
index 000000000..05e7c2f5f
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/TestCustomServiceProviderApp.csproj
@@ -0,0 +1,29 @@
+
+
+ Library
+ net8.0
+ enable
+ enable
+ true
+ Lambda
+
+ true
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Libraries/test/TestCustomServiceProviderApp/aws-lambda-tools-defaults.json b/Libraries/test/TestCustomServiceProviderApp/aws-lambda-tools-defaults.json
new file mode 100644
index 000000000..456fef59b
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/aws-lambda-tools-defaults.json
@@ -0,0 +1,15 @@
+{
+ "Information": [
+ "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
+ "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
+ "dotnet lambda help",
+ "All the command line options for the Lambda command can be specified in this file."
+ ],
+ "profile": "",
+ "region": "",
+ "configuration": "Release",
+ "s3-prefix": "TestHostBuilderApp/",
+ "template": "serverless.template",
+ "template-parameters": "",
+ "docker-host-build-output-dir": "./bin/Release/lambda-publish"
+}
\ No newline at end of file
diff --git a/Libraries/test/TestCustomServiceProviderApp/serverless.template b/Libraries/test/TestCustomServiceProviderApp/serverless.template
new file mode 100644
index 000000000..f84b297bc
--- /dev/null
+++ b/Libraries/test/TestCustomServiceProviderApp/serverless.template
@@ -0,0 +1,50 @@
+{
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Description": "An AWS Serverless Application. This template is partially managed by Amazon.Lambda.Annotations (v2.4.2.0).",
+ "Outputs": {
+ "ApiURL": {
+ "Description": "API endpoint URL for Prod environment",
+ "Value": {
+ "Fn::Sub": "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/"
+ }
+ }
+ },
+ "Resources": {
+ "TestCustomServiceProviderAppCustomServiceProviderFunctionsAddGenerated": {
+ "Metadata": {
+ "SyncedEventProperties": {
+ "RootGet": [
+ "Path",
+ "Method"
+ ]
+ },
+ "SyncedEvents": [
+ "RootGet"
+ ],
+ "Tool": "Amazon.Lambda.Annotations"
+ },
+ "Properties": {
+ "CodeUri": ".",
+ "Events": {
+ "RootGet": {
+ "Properties": {
+ "Method": "GET",
+ "Path": "/add/{x}/{y}"
+ },
+ "Type": "HttpApi"
+ }
+ },
+ "Handler": "TestProject::TestCustomServiceProviderApp.CustomServiceProviderFunctions_Add_Generated::Add",
+ "MemorySize": 512,
+ "PackageType": "Zip",
+ "Policies": [
+ "AWSLambdaBasicExecutionRole"
+ ],
+ "Runtime": "dotnet10",
+ "Timeout": 30
+ },
+ "Type": "AWS::Serverless::Function"
+ }
+ },
+ "Transform": "AWS::Serverless-2016-10-31"
+}
\ No newline at end of file