Home > database >  HttpClients and default AddScoped service
HttpClients and default AddScoped service

Time:10-19

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"});
  1. Why Microsoft didn't use AddSingleton for HttpClient?

  2. Is it necessary to use IHttpClientFactory instead of HttpClient?

  3. 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

CodePudding user response:

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

CodePudding user response:

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 it's 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 for HttpClient?

I would argue this question should be addressed to Microsoft

Is it necessary to use IHttpClientFactory instead of HttpClient?

In theory - no, but it is recommended approach to handle the complexities of http calls and HttpClient lifetime, cause 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.

  • Related