Below are two examples of using an httpClient in an azure function. The first is bad practice and the second one is best practice. My question is what exactly is the difference between the first and second example? Too me, it looks like the second example is just an abstraction of the first. Would it still not create a new httpClient every time the function is ran?
Bad Practice
[FunctionName("Function1")]
public async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer)
{
using (var httpClient = new HttpClient())
{
httpClient...
more code here...
}
}
Best Practice
[FunctionName("Function1")]
public async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, IHttpClientFactory clientFactory)
{
var httpClient = clientFactory.CreateClient();
httpClient...
}
CodePudding user response:
The factory pools HttpMessageHandler instances, and, if its lifetime hasn't expired, a handler can be reused from the pool when the factory creates a new HttpClient instance. This reuse avoids any socket exhaustion issues.
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines