0

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?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
steb
  • 436
  • 3
  • 12
  • 2
    Well, `services.AddHttpClient()` registers `IHttpClientFactory` with the container... I wonder why you haven't simply tried this out? – ProgrammingLlama Feb 03 '23 at 08:35

2 Answers2

1

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.

Mitko Petrov
  • 311
  • 1
  • 4
  • 12
  • Thank you, I think I understand now better. We have a lot of named + T-typed `AddHttpClient()` in the project, and that's why I don't need in this case the empty one, because any AddHttpClient(xxx) will do - to give access to the HttpClientFactory by the DI. So that's why it worked either way for me when I tested with or without the empty one. – steb Feb 03 '23 at 11:56
  • @steb There are actually 4 kinds of client that you can be register via `AddHttpClient`. Here you can read more about them: https://stackoverflow.com/questions/64286062/typed-httpclient-vs-ihttpclientfactory/64313603#64313603 – Peter Csala Feb 03 '23 at 12:41
0

The services.AddHttpClient(); in your startup class is used to configure an IHttpClientFactory instance, which is then used to create and manage named HttpClient instances.

If you are creating an instance of HttpClient directly with _httpClientFactory.CreateClient(), without specifying a named client,

what i suggest is you don't need to add the services.AddHttpClient(); line in the Startup class.

FACT: This line is necessary only if you plan to use the IHttpClientFactory to create named HttpClient instances.

for More visit: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-7.0