Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in AWS Lambda function using dotnet core 2.1

I am new to Aws Lambda and trying to figure out how to use Dependency Injection into Aws Lambda using .net core 2.1.

I am trying to inject IHttpClientFactory, but I am not sure if I am doing it correctly.

I am calling below method in the constructor of the lambda function class:

  private static IServiceProvider ConfigureServices()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddHttpClient("client", client =>
        {
            client.BaseAddress = new Uri("someurl");
        });

       return serviceCollection.BuildServiceProvider();
    }

Is this correct?

Also, after it returns IServiceProvider, how do I use it in any class where I need to call IHttpClientFactory?

(I have gone through some related articles, but I am still unclear to use the output from ConfigureServices() method when called in the constructor?)

Thanks.

Example of usage for DI:

public class Function
{
   private readonly ITestClass _test;
   public Function()
    {
       ConfigureServices();
    }

    public async Task Handler(ILambdaContext context)
    {
       _test.Run(); //Run method from TestClass that implements ITestClass and calls IHttpClientFactory to make call to an API

      //return something
    }

    private static void ConfigureServices()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddHttpClient("client", client =>
        {
            client.BaseAddress = new Uri("someurl");
        });
       serviceCollection.AddTransient<ITestClass, TestClass>();
       serviceCollection.BuildServiceProvider(); //is it needed??
    }
}
like image 771
coolio Avatar asked Sep 30 '18 17:09

coolio


1 Answers

Assign the service provider as the DI container and use it in your functions

Function.cs

public class Function {

    public static Func<IServiceProvider> ConfigureServices = () => {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddHttpClient("client", client =>
        {
            client.BaseAddress = new Uri("someurl");
        });
        serviceCollection.AddTransient<ITestClass, TestClass>();
        return serviceCollection.BuildServiceProvider();
    };

    static IServiceProvider services;
    static Function() {
        services = ConfigureServices();
    }


    public async Task Handler(ILambdaContext context) {
        ITestClass test = services.GetService<ITestClass>();
        await test.RunAsync(); 

        //...
    }
}

Using a static constructor for a one time call to configure your services and build the service container.

like image 135
Nkosi Avatar answered Oct 04 '22 02:10

Nkosi