Search code examples
c#.net-coredotnet-httpclienthttpclientfactory

Do I need to add all HttpClients?


If I use _httpClientFactory.CreateClient() in a singleton (no name for the client, I set it up when I use it)

Should I add/specify an empty services.AddHttpClient(); at startup or is that not necessary?


Solution

  • You should only specify empty services.AddHttpClient(); on startup. You could pass it name parameter if you want to configure "specific" HttpClient that you will later call by name (for example add base address or headers). Otherwise IHttpClientFactory will give you not configured one (like calling new HttpClient())

    For example:

    services.AddHttpClient("MyApiClient").ConfigureHttpClient(client =>
    {
        client.BaseAddress = new Uri(configuration["MyApiUrl"]);
    });
    

    and later calling factory like:

    _httpClientFactory.CreateClient("MyApiClient");
    

    will give you HttpClient with configured base address.