Reputation: 13467
Considering these topics:
https://stackoverflow.com/a/22561368/648723
https://stackoverflow.com/a/67067195/648723
https://stackoverflow.com/a/35045301/648723
They said: keep an instance of HttpClient for the lifetime of your application
But when we create a new Blazor
application, in Program.cs
file, the default HttpClient
registered as this:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = "MyUrl"});
Why Microsoft didn't use AddSingleton
for HttpClient
?
Is it necessary to use IHttpClientFactory
instead of HttpClient
?
If I want to use Multiple HttpClient
in my Blazor
application, How can I register and inject intended HttpClient
(With intended base URL) in my code?
Thanks
Upvotes: 0
Views: 3355
Reputation: 142823
They said: keep an instance of HttpClient for the lifetime of your application
While it was a preferred approach for quite a long time but it has its drawbacks - for example handling DNS changes (though based on this comment it can be worked around by changing SocketsHttpHandler.PooledConnectionLifetime
property to something else from the default InfiniteTimeSpan
)
Why Microsoft didn't use
AddSingleton
forHttpClient
?
I would argue this question should be addressed to Microsoft
Is it necessary to use
IHttpClientFactory
instead ofHttpClient
?
In theory - no, but it is recommended approach to handle the complexities of http calls and HttpClient
lifetime, because most of them should be handled by the IHttpClientFactory
and in general you will not need to care.
If I want to use Multiple HttpClient in my Blazor application, How can I register and inject intended HttpClient (With intended base URL) in my code?
It can be easily achieved with IHttpClientFactory
by setting it up in the DI either with named clients or typed clients.
Upvotes: 1
Reputation: 1671
The topics you link say to create an instance of HttpClient per API you're connecting to which is an important difference.
AddSingleton
would only make sense if you're sure your application will only ever connect to one specific API.
You can instantiate an HttpClient just fine, but the factory pattern contains a lot of optimization on when to create a new instance or to reuse an existing instance. It also prevents you from running out of sockets which will happen if you have too many HttpClient instances at once. See here for more: https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore
This post shows how to define multiple named HttpClients for different URLs: https://www.stevejgordon.co.uk/httpclientfactory-named-typed-clients-aspnetcore
Upvotes: 2