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?
CodePudding user response:
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.
CodePudding user response:
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