Search code examples
c#.netdependency-injectiondotnet-httpclient

IHttpClientFactory cache not working as expected


I might misunderstand the workings of the IHttpClientFactory, basically what I want to do is in my asp.net core project is create a cached client at runtime in for example my controller.

Example:

Program.cs
...
builder.Services.AddHttpClient();
...

Then in my controller (just the default asp.net core project from Microsoft as example)

public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        public IndexModel(ILogger<IndexModel> logger, IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
        }

        public void OnGet()
        {
            var test = _httpClientFactory.CreateClient("test");
            test.BaseAddress = new Uri("https://google.com/");

            var test2 = _httpClientFactory.CreateClient("test");
        }
    }

What I expected is at test2 my client would have set the default base address to https://google.com, this is unfortunately not the case however. All custom headers and/or base-addresses are un-set.

I was under the impression that the HttpClientFactory would store this in-memory. Am I misunderstanding the workings of the HttpClientFactory or am I missing something else? Note: I cannot define this in program.cs, it has to be done like above (if possible at all).


Solution

  • The life cycle management

    An HttpClient's life cycle is short, but the underlying HttpClientMessageHandlers are pooled.
    (related source code)

    Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes

    CreateClient method call

    This method is creating a lightweight HttpClient instance. It calls the CreateHandler method which fetches the underlying pooled HttpMessageHandler.

    So, the observed behaviour is the expected one.