Use IHttpClientFactory to implement resilient HTTP requests

Benefits of using IHttpClientFactory

  • Provides a central location for naming and configuring logical HttpClient objects. For example, you may configure a client (Service Agent) that’s pre-configured to access a specific microservice.
  • Codify the concept of outgoing middleware via delegating handlers in HttpClient and implementing Polly-based middleware to take advantage of Polly’s policies for resiliency.
  • HttpClient already has the concept of delegating handlers that could be linked together for outgoing HTTP requests. You can register HTTP clients into the factory and you can use a Polly handler to use Polly policies for Retry, CircuitBreakers, and so on.
  • Manage the lifetime of xref:System.Net.Http.HttpMessageHandler to avoid the mentioned problems/issues that can occur when managing HttpClient lifetimes yourself.

Multiple ways to use IHttpClientFactory

There are several ways that you can use IHttpClientFactory in your application:

  • Basic usage
  • Use Named Clients
  • Use Typed Clients
  • Use Generated Clients

source