简体   繁体   中英

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??
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM