HttpLifetimeFactory
Namespace: System.Net.Http
Represents a factory for creating and managing the lifetime of HttpClient instances.
This class is used to provide a centralized mechanism for configuring and disposing of HttpClient objects, promoting efficient resource utilization and consistent behavior across an application.
Summary
The HttpLifetimeFactory class is designed to simplify the management of HttpClient instances within a .NET application. It allows developers to define default configurations for HttpClient, such as base addresses, default headers, and timeouts. Additionally, it facilitates the proper disposal of these clients, preventing resource leaks and improving performance.
Key features include:
- Centralized configuration of
HttpClient. - Managed lifetime and disposal of
HttpClientinstances. - Support for creating typed clients derived from interfaces.
- Integration with dependency injection containers.
Class Members
The HttpLifetimeFactory class exposes the following members:
Constructors
| Signature | Description |
|---|---|
HttpLifetimeFactory()
|
Initializes a new instance of the HttpLifetimeFactory class. |
Methods
| Signature | Description |
|---|---|
CreateClient(string name)
|
Creates a new HttpClient instance with the specified name. |
CreateClient()
|
Creates a new default HttpClient instance. |
Dispose()
|
Releases all resources used by the HttpLifetimeFactory. |
Dispose(bool disposing)
|
Releases the unmanaged resources used by the HttpLifetimeFactory and optionally releases the managed resources. |
Usage Example
Here's a simple example demonstrating how to use HttpLifetimeFactory to create and manage an HttpClient:
// Assume HttpLifetimeFactory is registered in DI or instantiated directly
var factory = new HttpLifetimeFactory();
// Create a named client
var namedClient = factory.CreateClient("MyApiClient");
namedClient.BaseAddress = new Uri("https://api.example.com/");
// Create a default client
var defaultClient = factory.CreateClient();
// Use the clients...
// When the application is shutting down or the factory is no longer needed, dispose it.
((IDisposable)factory).Dispose();