【发布时间】:2018-10-01 03:12:06
【问题描述】:
我是 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??
}
}
【问题讨论】:
-
到目前为止你所拥有的都是可用的。至于您的其他问题,您需要显示一些代码来帮助证明您正在尝试这样做。显示带有上面包含的 sn-p 的示例函数。
标签: c# dependency-injection .net-core aws-lambda