Search code examples
c#.net-6.0dotnet-httpclientblazor-webassembly

HttpClients and default AddScoped service


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


Solution

  • 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