Table of Contents

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 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

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

Initializes a new instance of the SlimHttpClientFactory class.

public SlimHttpClientFactory(Func<HttpClientHandler> handlerFactory, Action<SlimHttpClientFactoryOptions> setup = null)

Parameters

handlerFactory Func<HttpClientHandler>

The function delegate that creates and configures an HttpClientHandler.

setup Action<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

name string

The 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

name string

The logical name of the message handler to create.

Returns

HttpMessageHandler

A new HttpMessageHandler instance.

See Also