使用 dotnet core 2.1 在 AWS Lambda 函数中进行依赖注入

coo*_*lio 6 c# dependency-injection .net-core aws-lambda

我是 Aws Lambda 的新手,并试图弄清楚如何使用 .net core 2.1 将依赖注入用于 Aws Lambda。

我正在尝试注射IHttpClientFactory,但我不确定我是否正确地进行了注射。

我在 lambda 函数类的构造函数中调用以下方法:

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

       return serviceCollection.BuildServiceProvider();
    }
Run Code Online (Sandbox Code Playgroud)

这样对吗?

此外,在它返回后IServiceProvider,我如何在需要调用的任何类中使用它IHttpClientFactory

(我看了一些相关的文章,但我还是不清楚ConfigureServices()在构造函数中调用时使用方法的输出?)

谢谢。

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??
    }
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

将服务提供者指定为 DI 容器并在您的函数中使用它

函数.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(); 

        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

使用静态构造函数进行一次调用来配置您的服务并构建服务容器。