Alternative approach to HttpClient in Azure Functions 2.0 - bringing in HttpClientFactory

11 gru 2018 | Blog | azure functions | httpclient | httpclientfactory | IT

This post no longer describes the best approach. You can read the revisited version here.


HttpClient is not as straightforward to use as it may seem. A lot has been written about improper instantiation antipattern. Long story short, you shouldn't be creating a new instance of HttpClient whenever you need it, you should be reusing them. In order to avoid this antipattern, many technologies provide guidance for efficient usage of HttpClient, Azure Functions are no different. The current recommendation is to use a static client, something like the code below.

public static class PeriodicHealthCheckFunction
{
private static HttpClient _httpClient = new HttpClient();

[FunctionName("PeriodicHealthCheckFunction")]
public static async Task Run(
[TimerTrigger("0 */5 * * * *")]TimerInfo healthCheckTimer,
ILogger log)
{
string status = await _httpClient.GetStringAsync("https://localhost:5001/healthcheck");

log.LogInformation($"Health check performed at: {DateTime.UtcNow} | Status: {status}");
}
}

This approach avoids the socket exhaustion problem and brings performance benefits, but creates another problem. Static HttpClient doesn't respect DNS changes. Sometimes this might be irrelevant, but sometimes it might lead to serious issues. Is there a better approach?

HttpClientFactory

One of the areas where both sides of HttpClient instantiation problem are often encountered is ASP.NET Core. Two most common use cases for ASP

POSTY TEGO AUTORA

Monitoring C# Azure Functions in the Isolated Worker Model - Infrastructure & Configuration Deep Dive26 lis 2024

Blog | programowanie | .net | c# | azure functions | IT

ASP.NET Core 9 and IAsyncEnumerable - Async Streaming JSON and NDJSON From Blazor WebAssembly24 wrz 2024

Blog | programowanie | .net | c# | asp.net core | blazor | IT

Azure Functions Extensibility - Extensions and Isolated Worker Model5 mar 2024

Blog | programowanie | .net | c# | azure functions | azure | IT

Azure Functions Extensibility - Runtime Scaling22 lut 2024

Blog | programowanie | .net | c# | azure | IT

Yet Another Developer Blog

noreply@blogger.com (Tomasz Pęczek)