HttpClientFactory
HttpClient
.NET
dependency injection
C#
HttpClientFactory.Create vs new HttpClient
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Overview
When developing applications that interact with web services in .NET, HttpClient
is a commonly used class. However, using HttpClient
incorrectly can lead to various problems, such as socket exhaustion and DNS changes being ignored. To tackle these issues, HttpClientFactory
was introduced, offering an efficient way to manage HttpClient
instances.
This article explores the differences between HttpClientFactory.Create
and using new HttpClient
, delving into their technical details, advantages, and potential pitfalls.
HttpClient
Instantiation
new HttpClient
Traditionally, developers use the new
keyword to create HttpClient
instances:
- Simplicity: Quick and straightforward, allows for immediate creation of an
HttpClient. - Control: Gives complete freedom on configuration and lifecycle management.
- Resource Management: Each instance consumes a socket connection, which, if not disposed of correctly, can lead to socket exhaustion, especially under high load.
- DNS and Service Discovery:
HttpClientdoes not automatically update DNS entries for its lifetime. Long-lived instances may miss DNS changes (e.g., server scaling or failover). - Connection Management: Each instance maintains its own connection pool, which is inefficient.
- Lifecycle Management: Automatically manages the lifecycle of
HttpClientinstances, mitigating socket exhaustion by reusing existing connections. - Improved DNS Support: Periodically refreshes DNS resolutions, adapting to changes.
- Centralized Configuration: Supports easier and centralized configuration through dependency injection.
- Named and Typed Clients: Allows configuration of specific clients by name or type, providing tailored settings for different services.
- Complexity: Adds extra complexity by introducing a factory pattern, which might overcomplicate simple applications.
- Overhead: Slight overhead in creating
HttpClientinstances via the factory as compared to direct instantiation, though generally negligible. - **
new HttpClient**: Would require numerous disposable instances, risking socket exhaustion as connections are not reused. - **
HttpClientFactory**: Reuses connections and manages pooling effectively, preventing operational issues. - **
new HttpClient**: Instances won't reflect DNS changes, potentially routing traffic to obsolete service instances. - **
HttpClientFactory**: Automatically resolves DNS changes, ensuring traffic direction to active nodes.

