Anders Sewerin Johansen
Anders Sewerin Johansen

Reputation: 1656

Adding a SocketsHttpHandler to an HttpClient created via AddHttpClient in Startup.cs?

I'd like to add a SocketsHttpHandler to an HttpClient that I am creating via AddHttpClient in Startup.cs. The point of that is to be able to inject instrumentation etc. in the HttpClient via a factory.

This does not give me the option to use the constructor of HttpClient, which is where you'd usually add a SocketsHttpHandler.

Also, I don't see any obvious property etc. I can use to add it later.

Upvotes: 8

Views: 4658

Answers (2)

JJS
JJS

Reputation: 6658

services.AddHttpClient(name)
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new SocketsHttpHandler()
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(2)
        };
    })
    .SetHandlerLifetime(Timeout.InfiniteTimeSpan); // Disable rotation, as it is handled by PooledConnectionLifetime
  1. Specify SocketsHttpHandler as PrimaryHandler and set up its PooledConnectionLifetime (for example, to a value that was previously in HandlerLifetime).
  2. As SocketsHttpHandler will handle connection pooling and recycling, then handler recycling at the IHttpClientFactory level is not needed anymore. You can disable it by setting HandlerLifetime to Timeout.InfiniteTimeSpan.

https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#using-ihttpclientfactory-together-with-socketshttphandler

Upvotes: 0

Anders Sewerin Johansen
Anders Sewerin Johansen

Reputation: 1656

...aaaand as is traditional I found the answer five minutes later. Never matters how long you look before, does it now?

How I can change configuration of HttpMessageHandler from Polly retry?

.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
           {
               MaxConnectionsPerServer = 3,
           })

Upvotes: 15

Related Questions