Use HttpClientFactory Over HttpClient in .NET

Let's break down the benefits of using HttpClientFactory over directly using HttpClient in .NET Core with a simple example.

Why Use HttpClientFactory?

Imagine you're building a web app that needs to fetch data from an external service. You can think of HttpClient as a delivery service. If you keep ordering a new delivery service for every single request, it gets inefficient and messy. Instead, having a factory that provides a well-managed delivery service makes everything smoother and more efficient.

Direct Use of HttpClient

If you use HttpClient directly, it might look something like this.

public class MyService
{
    private readonly HttpClient _httpClient;
    public MyService()
    {
        _httpClient = new HttpClient(); // New instance every time
    }
    public async Task<string> GetDataAsync()
    {
        var response = await _httpClient.GetStringAsync("https://test.example.com/data");
        return response;
    }
}

Problem: Creating a new HttpClient instance every time can lead to issues like running out of resources.

Using HttpClientFactory

Now, let’s see how using HttpClientFactory makes things easier and more efficient.

Setup

First, you set up HttpClientFactory in your app’s startup configuration. This is like telling your app where to get its delivery service from.

// In Startup.cs or Program.cs
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Register HttpClientFactory
        services.AddHttpClient();
    }
}

​​​​​​Use the Factory

Now, in your service class, you use the factory to get HttpClient instances. This is like asking the factory for a delivery service whenever you need it.

public class MyService
{
    private readonly HttpClient _httpClient;
    public MyService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient(); // Get a managed HttpClient instance
    }
    public async Task<string> GetDataAsync()
    {
        var response = await _httpClient.GetStringAsync("https://test.example.com/data");
        return response;
    }
}

In your application, you tell it to use the factory to provide MyService.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        services.AddTransient<MyService>();
    }
}

And you use MyService like this.

public class MyController : ControllerBase
{
    private readonly MyService _myService;
    public MyController(MyService myService)
    {
        _myService = myService;
    }
    public async Task<IActionResult> Get()
    {
        var data = await _myService.GetDataAsync();
        return Ok(data);
    }
}

Summary

  • Without HttpClientFactory: You’re constantly ordering new delivery services, which can cause problems.
  • With HttpClientFactory: You have a factory that manages your delivery services, making it more efficient and organized.