How to use Dependency Injection in AWS Lambda C# implementation

aws lambda dependency injection
aws lambda dependency injection nodejs
aws sdk dependency injection c#
.net standard dependency injection
aws lambda environment variables c#
dynamodb dependency injection
aws lambda entity framework
aws-lambda-tools-defaults json

I have created Lambda functions using AWS.Net SDK, .net core version 1.0. I want to implement dependency injection. Since lambda functions triggered and run independently in AWS environment, there is no such class like Startup present. How and Where can I configure my containers to achieve this implementation?


You can do this. Your FunctionHandler is your entry point to your application.. so you have to wire up the service collection from there.

public class Function
{
    public string FunctionHandler(string input, ILambdaContext context)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        // create service provider
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // entry to run app.
        return serviceProvider.GetService<App>().Run(input);
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        // add dependencies here

        // here is where you're adding the actual application logic to the collection
        serviceCollection.AddTransient<App>();
    }
}

public class App
{
    // if you put a constructor here with arguments that are wired up in your services collection, they will be injected.

    public string Run(string input)
    {
        return "This is a test";
    }
}

If you want to wire up logging, have a look here: https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.Logging.AspNetCore

How to use Dependency Injection in AWS Lambda C# implementation, You can do this. Your FunctionHandler is your entry point to your application.. so you have to wire up the service collection from there. Add .net core Dependency Injection to lambda. Anytime you directly create an object you are coupling yourself to a specific implementation. So it stands to reason that you’d want to apply the same Inversion of Control pattern and .NET Core Dependency Injection goodness to your AWS Lambda Functions as you would in a standard ASP.NET Core Web API


While the FunctionHandler is indeed your entry point to your application, I would actually wire up your DI in a parameterless constructor. The constructor only ever gets called once, so this purely "setup" code should really only need to be called once. We just want to take advantage of using it in every subsequent invocation that gets routed to the same container.

public class Function
{
    private static ServiceProvider ServiceProvider { get; set; }

    /// <summary>
    /// The parameterless constructor is what Lambda uses to construct your instance the first time.
    /// It will only ever be called once for the lifetime of the container that it's running on.
    /// We want to build our ServiceProvider once, and then use the same provider in all subsequent 
    /// Lambda invocations. This makes things like using local MemoryCache techniques viable (Just 
    /// remember that you can never count on a locally cached item to be there!)
    /// </summary>
    public Function()
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        ServiceProvider = services.BuildServiceProvider();
    }

    public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context)
    {
        await ServiceProvider.GetService<App>().Run(evnt);
    }

    /// <summary>
    /// Configure whatever dependency injection you like here
    /// </summary>
    /// <param name="services"></param>
    private static void ConfigureServices(IServiceCollection services)
    {
        // add dependencies here ex: Logging, IMemoryCache, Interface mapping to concrete class, etc...

        // add a hook to your class that will actually do the application logic
        services.AddTransient<App>();
    }

    /// <summary>
    /// Since we don't want to dispose of the ServiceProvider in the FunctionHandler, we will
    /// at least try to clean up after ourselves in the destructor for the class.
    /// </summary>
    ~Function()
    {
        ServiceProvider.Dispose();
    }
}

public class App
{
    public async Task Run(SQSEvent evnt)
    {
        // actual business logic goes here
        await Task.CompletedTask;
    }
}

Dependency Injection in AWS Lambda function using dotnet core 2.1, Assign the service provider as the DI container and use it in your functions. Function.cs public class Function { public static  In this sample we have enable our lambda to make use of some great .net core features of dependency Injection and Configuration. This will enable developers to de-clutter their lambda functions and help to organise their code and also enable the use of additional libraries.


I know I am way late to the game but I am adding this because I believe there are some bad/lacking examples out on the internet. @Erndob is right about the accepted answer. You'll just be creating more instances.

Depending on what registrations you are making in your DI container you need to keep in mind:

  1. What registrations are you making that implement IDisposable
  2. How long does AWS keep the instance of your object around. I have not been able to find any documentation on this.

Ended up going with something like this:

public class Function
{
    private ServiceCollection _serviceCollection;

    public Function()
    {
        ConfigureServices();
    }

    public string FunctionHandler(string input, ILambdaContext context)
    {
        using (ServiceProvider serviceProvider = _serviceCollection.BuildServiceProvider())
        {
            // entry to run app.
            return serviceProvider.GetService<App>().Run(input);
        }
    }

    private void ConfigureServices()
    {
        // add dependencies here
        _serviceCollection = new ServiceCollection();
        _serviceCollection.AddTransient<App>();
    }
}

With this pattern each lambda invocation will get a new ServiceProvider and dispose of it when finished.

Add .NET Core DI and Config Goodness to AWS Lambda Functions , Add Dependency Injection Code​​ So it stands to reason that you'd want to apply the same Inversion of Control pattern and . NET Core Dependency Injection goodness to your AWS Lambda Functions as you would in a standard ASP.NET Core Web API project. Start by adding a package reference to Microsoft. Extensions. Select AWS Lambda Project with Tests. Add an appsettings.json file to the project. Add an appsettings.Development.json file to the project. Select both JSON files, open the Propeties window of Visual Studio, then set the BuildAction property to Content and the Copy to Output Directory property to Copy always.


If you are talking about dependency injection of AWS Services for WebAPI it is possible if you use AspNetCoreWebAPI template via dotnet new lambda.AspNetCoreWebAPI or Visual Studio blueprints

This template has Startup class (of course each startup is executed once per lambda environment like you mentioned). You add add AWS services in ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
  // Add service to obtain in Controllers constructor
  services.AddAWSService<IAmazonDynamoDB>();
}

Then use the constructor for the dependency injection your Controller class

IAmazonDynamoDB client;
public ValuesController(IAmazonDynamoDB dbClient)
{
    this.client = dbClient;
}

These services are started with credentials retrieved from Environment variables, therefore make sure you include your AWS profile in appsettings.json. If you are not sure about appsettings.json or how to declare profiles according to the ASPNETCORE_ENVIRONMENT leave a comment.

Working with dependency injection in .NET Standard: inject your , Let's take a look at a simple demo application. Demo.cs. C#. using System.​Threading.Tasks; using Amazon  Using a static Lazy<T> initializer to return an IServiceProvider instance with configuration settings, interfaces, and implementation classes, the serverless function can take advantage of the .NET dependency injection framwork. This approach provides a path forward to migrate a business logic from a Web API to serveless functions.


Discussion of Simple Dependency Injection In AWS Lambda .net core, Let's take a look at the example from part 1, rewritten to use the Generic Host. To recap, this application simply lists out all Amazon S3 buckets  AWS Lambda Function Errors in C# Javascript is disabled or is unavailable in your browser. To use the AWS Documentation, Javascript must be enabled.


Dependency Injection With Serverless Functions, I've previously discussed how to develop a .net core AWS Lambda with the server. Simple Dependency Injection In AWS Lambda .net core Say I want to use a mocked ILambdaConfiguration instance; with the My question was how would you unit test a serverless function like the one in your example  You'll face a problems when it comes to unit testing your code, because you have no way to substitute implementation of DynamoDBContext. The proper way is to register DynamoDBContext in DI container and let the container itself create an instance when it's required.


Some Useful Patterns for C# AWS Lambda Functions, This article demonstrates how to bootstrap AWS Lambda and Azure Serverless and interface implementations into a dependency injection framework. Azure Functions pull their configuration settings from application and  Using Async in C# Functions with AWS Lambda If you know your Lambda function will require a long-running process, such as uploading large files to Amazon S3 or reading a large stream of records from DynamoDB, you can take advantage of the async/await pattern.