Search code examples
c#.net-coreaws-lambda

How to use Dependency Injection in AWS Lambda C# implementation


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?


Solution

  • 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