Simple Dependency Injection In AWS Lambda .net core
Tags: csharp, aws, dotnet, serverless
Published: 2019-04-25 20:32:40

---
title: Simple Dependency Injection In AWS Lambda .net core
published: true
tags: Csharp,AWS,dotnet,serverless
canonical_url: https://garywoodfine.com/dependency-injection-in-aws-lambda/
---

I’ve previously discussed how to [develop a .net core AWS Lambda with the serverless framework](https://garywoodfine.com/net-core-serverless-framework/)to provide an abstraction over the underlying operating system and execution runtime so that you can more easily achieve economies of scale using Cloud computing paradigms.

In this post, I will expand on these concepts and provide an introduction on how you can introduce concepts like dependency injection and configuration to your lambda functions.

Serverless Framework enables you to easily create and manage resources used by your Lambda components and creates a simple stub function enabling you to focus on developing your function.

The one problem with this is that developers may perceive that they can’t implement all the usual good things you would in any other development project and judging from some of the code I have had to deal with out in the wild this certainly is true!

{% github garywoodfine/HelloConfiguration %}


## AWS Lambda and .net core

AWS Lambda supports a number of [programming languages and runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html), well [custom runtimes](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html) which enable the use of any language and execution environment. Included in the list of standard runtimes is Microsoft [.NET Core](https://en.wikipedia.org/wiki/.NET_Core), an open-source cross-platform runtime, which you can build apps on using the [C# programming language](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)).

When generating a project using the serverless framework template is that it lacks the usual hooks for setting up configuration and dependency injection. Youâre on your own for adding the necessary code. I will walk you through the process of implementing all the boilerplate code required.

To generate a new serverless lambda project we’ll use the following Serverless command:

```bash
sls create -t  aws-csharp -p HelloConfiguration -n Threenine.ConfigTest

```

Information

To learn how to install the Serverless Framework and what these commands do I urge you to read [Getting started with .NET Core and the Serverless Framework](https://dev.to/gary_woodfine/getting-started-with-net-core-and-the-serverless-framework-1kge-temp-slug-5669462)

Once the project has been generated we can set to work clearing out the `Handler.cs` and remove most of the code there so we’re only left with the following

```c#
using Amazon.Lambda.Core;
using System;

[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AwsDotnetCsharp
{
    public class Handler
    {
     
    }
}

```

### 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](https://en.wikipedia.org/wiki/Inversion_of_control)pattern and [.NET Core Dependency Injection](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2) goodness to your AWS Lambda Functions as you would in a standard [ASP.NET Core Web API](https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2) project.

The additional benefit of making use of IOC and Dependency Injection code in an AWS Lambda project is that you can eventually make use of [AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) which enable you to configure your Lambda function to pull in additional code and content in the form of layers.

A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package.

First, we need to wire up dependency injection, so in order to do that add the following references to our project

```bash
dotnet add package Microsoft.Extensions.Hosting –version 2.1.0
dotnet add package Microsoft.Extensions.Configuration –version 2.1.0
dotnet add package Microsoft.Extensions.Configuration.Json –version 2.1.0

```

Note the version number, this is due to fact **AWS lambda currently only supports .net core 2.1.0.**

In our next step lets add a new Interface which we’ll name `ILambdaConfiguration.cs`

```c#
using Microsoft.Extensions.Configuration;

namespace AwsDotnetCsharp
{
    public interface  ILambdaConfiguration
    {
        IConfiguration Configuration { get; }
    }
}

```

### Implement Lambda Configuration

We can now add a class that will implement the interface we’ll imaginatively call this `LambdaConfiguration.cs`



Initially, we are going to enable our Lambda to read configuration settings from an `appsettings.json` file so before we add the code to do so add the file to your project. Just add an empty `json` file, by convention .net developers name this file `appsettings.json` but you can call it whatever you want.

Your aws-csharp.csproj should now look something similar to this

```xml

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AssemblyName>CsharpHandlers</AssemblyName>
    <PackageId>aws-csharp</PackageId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="1.0.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.Json" Version="1.3.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.0" />
       <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <None Remove="appsettings.json" />
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>

```




We can edit the LambdaConfiguration to get data from our App Settings

```c#
using System.IO;
using Microsoft.Extensions.Configuration;

namespace AwsDotnetCsharp
{
     public class LambdaConfiguration : ILambdaConfiguration
    {
        public IConfiguration Configuration  => new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

       
    }
    }
}

```


We can now complete the code from our simple lambda. So edit the Handler.cs to contain the following code.

```c#
using Amazon.Lambda.Core;
using Microsoft.Extensions.DependencyInjection;

[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AwsDotnetCsharp
{
    public class Handler
    {
        private ILambdaConfiguration Configuration { get; }

        public Handler()
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();
            Configuration = serviceProvider.GetService<ILambdaConfiguration>();
        }
        
        public string Hello( ILambdaContext context)
        {
            return LambdaConfiguration.Configuration["hello"] ?? "None";
        }
        
        private void ConfigureServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient<ILambdaConfiguration, LambdaConfiguration>();
        }
     
    }
}


```


All this code is basically doing is wiring up the dependency injection and configuring the application. Online 20 we have created a simple Hello lambda method and the only thing it does is read a value from the app settings file, a key which we have called hello.

Our App Settings file is rather simple and looks like

```bash
{
    "hello": "This is from the configuration"
}


```

## Build and Deploy the Lambda

We can now build and deploy our lambda using Serverless Framework. I typically work on my Linux box so I will build the application making use of the `build.sh.` I have kept the yaml file really simple and it contains the following

```
service: Hello-Configuration # NOTE: update this with your service name

provider:
  name: aws
  runtime: dotnetcore2.1

package:
  individually: true

functions:
  hello:
    handler: CsharpHandlers::AwsDotnetCsharp.Handler::Hello

 
    package:
      artifact: bin/release/netcoreapp2.1/hello.zip


```

Using the build command

```bash
sudo ./build.sh

```


Then once the build has completed we can simply deploy our application to AWS using

```bash

sls deploy

```

after the deploy has completed we can simply test our function by invoking it as follows

```bash

sls invoke -f hello

```
We should then see the response printed of whatever the value you placed in the appsettings file

## Summary

In this simple tutorial, we have discovered how to implement a basic implementation of Dependency Injection and we have also provided an example of how you can make use of application configuration to make use of appsettings to store additional configuration information for your AWS Lambda and read this information at run time.

If you want to learn more advanced techniques on how to implement dependency injection in AWS Lambda with .net core check out [Serverless AWS Lambda Dependency Injection]( https://garywoodfine.com/serverless-aws-lambda-dependency-injection )