Table of Contents

SlimHttpClientFactory Class

Definition

Namespace
Cuemon.Extensions.Net.Http
Assemblies
Cuemon.Extensions.Net.dll
Source
src/Cuemon.Extensions.Net/Http/SlimHttpClientFactory.cs

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 to create named instances with a shared handler pool and configurable lifetime.

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

Constructors

Name Description
SlimHttpClientFactory(Func<HttpClientHandler>, Action<SlimHttpClientFactoryOptions>)

Initializes a new instance of the SlimHttpClientFactory class.

Methods

Name Description
CreateClient(string)

Creates and configures an HttpClient instance using the configuration that corresponds to the logical name specified by name.

CreateHandler(string)

Creates and configures an HttpMessageHandler instance using the configuration that corresponds to the logical name specified by name.

See Also