Class SlimHttpClientFactory
- Namespace
- Cuemon.Extensions.Net.Http
- Assembly
- Cuemon.Extensions.Net.dll
Provides a simple and lightweight implementation of the IHttpClientFactory interface.
public class SlimHttpClientFactory : IHttpClientFactory, IHttpMessageHandlerFactory
- Inheritance
-
SlimHttpClientFactory
- Implements
- Extension Methods
Examples
The following example demonstrates how to use
using System;
using System.Net.Http;
using Cuemon.Extensions.Net.Http;
namespace MyApp.Examples;
public class SlimHttpClientFactoryExample
{
public void Demonstrate()
{
// Create a factory that reuses HttpClientHandler instances per name
var factory = new SlimHttpClientFactory(
() => new HttpClientHandler
{
AllowAutoRedirect = false,
MaxAutomaticRedirections = 5
});
// Create two named clients - they share the same handler pool
using var clientA = factory.CreateClient("ServiceA");
using var clientB = factory.CreateClient("ServiceB");
clientA.BaseAddress = new Uri("https://service-a.example.com");
clientB.BaseAddress = new Uri("https://service-b.example.com");
Console.WriteLine($"ClientA base: {clientA.BaseAddress}");
Console.WriteLine($"ClientB base: {clientB.BaseAddress}");
// The handler for "ServiceA" is reused across calls to CreateClient("ServiceA")
// until the configured handler lifetime expires.
}
}
Remarks
Inspiration taken from https://github.com/dotnet/runtime/blob/master/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs
Constructors
SlimHttpClientFactory(Func<HttpClientHandler>, Action<SlimHttpClientFactoryOptions>)
Initializes a new instance of the SlimHttpClientFactory class.
public SlimHttpClientFactory(Func<HttpClientHandler> handlerFactory, Action<SlimHttpClientFactoryOptions> setup = null)
Parameters
handlerFactoryFunc<HttpClientHandler>The function delegate that creates and configures an HttpClientHandler.
setupAction<SlimHttpClientFactoryOptions>The SlimHttpClientFactoryOptions which may be configured.
Methods
CreateClient(string)
Creates and configures an HttpClient instance using the configuration that corresponds to the logical name specified by name.
public HttpClient CreateClient(string name)
Parameters
namestringThe logical name of the client to create.
Returns
- HttpClient
A new HttpClient instance.
CreateHandler(string)
Creates and configures an HttpMessageHandler instance using the configuration that corresponds to the logical name specified by name.
public HttpMessageHandler CreateHandler(string name)
Parameters
namestringThe logical name of the message handler to create.
Returns
- HttpMessageHandler
A new HttpMessageHandler instance.