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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With