Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
In this post, we will understand how can we implement the following things when using AWS Lambda with .NET Core.
When we create an AWS Lambda project in Visual Studio, we just get the basic FunctionHandler
method inside Function
class.
.NET Core features such as Configuration, Logging & Dependency Injection are not enabled by default. We need to write some additional code to enable these features.
Although, Logging is enabled by default, that uses the lambda logger, not the .NET Core's default logger.
We will be implementing the following things in this post further.
appsettings.json
file & Environment Variables
.Console
logging.ServiceCollection
.We would need the below packages to implement Configuration, Logging & Dependency Injection in our Lambda project. Just update csproj
file to have ItemGroup
section like below, or install these packages manually.
Startup
class fileCreate a Startup.cs
class file with the below content. Code is self-explanatory.
You may also need to add the below namespaces.
LambdaEntryPoint
classCreate LambdaEntryPoint
class with Handler
method. Inject all the dependencies inside the constructor of this class. We will invoke Handler
method of this class from the original FunctionHandler
.
ILambdaEntryPoint
interfaceLambdaEntryPoint
classFunction.cs
classNow replace Function
class content with the below content.
Here, we are mainly doing 2 things:
ConfigureServices()
method of Startup
class. This method will register all the services in ServiceCollection
and return an instance of IServiceProvider
.FunctionHandler
, we are calling _lambdaEntryPoint.Handler(input)
method to do the actual processing.Also, it is important to understand, Function
class is Singleton in AWS Lambda. Multiple invocations of AWS Lambda will not execute Constructor logic multiple times, which will be executed only once in the beginning, and the class will remain singleton until the Lambda compute is alive.
That's all.
In this post, we learned how easily we can set up configuration, logging and dependency injection in AWS Lambda when using with .NET Core. Please let me know your thoughts and feedback in the comment section below.
Thank You ❤️