使用dotnet core 2.1的AWS Lambda函数中的依赖项注入

时间:2018-09-30 17:56:37

标签: 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();
    }

这正确吗?

此外,在返回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??
    }
}

1 个答案:

答案 0 :(得分:2)

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

Function.cs

<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>

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