How to use Typed Clients with IHttpClientFactory to implement resilient HTTP requests?

Views: 1014
Comments: 0
Like/Unlike: 0
Posted On: 02-Mar-2023 03:36 

Share:   fb twitter linkedin
Rahul M...
Teacher
4822 Points
23 Posts

 

The well-known HttpClient class can be easily used, but in some scienario, it isn't does not work properly. Although HttpClient class implements IDisposable even declaring and instantiating it within a using statement is not preferred because when the HttpClient object gets disposed of, the underlying socket is not immediately released, which can cause to a socket exhaustion problem. Instantiating an HttpClient class for each request will exhaust the number of sockets available and issue will result in SocketException errors. Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. 

Using Typed Clients with IHttpClientFactory is a great way to implement resilient HTTP requests in .NET. 

How to do it?

 

  1. Create a client interface:
    public interface IMyApiClient
    {
        Task<MyApiResponse> GetAsync();
    }
  2. Implement the client interface:
    public class MyApiClient : IMyApiClient
    {
        private readonly HttpClient _httpClient;

        public MyApiClient(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<MyApiResponse> GetAsync()
        {
            var response = await _httpClient.GetAsync("https://api.example.com/my-resource");

            if (!response.IsSuccessStatusCode)
            {
                throw new MyApiException(response.StatusCode);
            }

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseObject = JsonConvert.DeserializeObject<MyApiResponse>(responseContent);

            return responseObject;
        }
    }
  3. Register the client interface and implementation with the service container in program.cs:
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();

    builder.Services.AddHttpClient<IMyApiClient, MyApiClient>();
  4. Use the client interface in your code:
    public class MyService
    {
        private readonly IMyApiClient _myApiClient;

        public MyService(IMyApiClient myApiClient)
        {
            _myApiClient = myApiClient;
        }

        public async Task<MyApiResponse> DoSomethingAsync()
        {
            return await _myApiClient.GetAsync();
        }
    }

 

Using Typed Clients with IHttpClientFactory and Polly provides a flexible and powerful way to implement resilient HTTP requests in your .NET application.

 

 

0 Comments
 Log In to Chat