Home > Blockchain >  Why does Blazor template use a factory to create HttpClient instances
Why does Blazor template use a factory to create HttpClient instances

Time:05-01

When diposing an HttpClient, one can run into the "socket exhaustion" problem. So the standard advice is to reuse the client whenever possible.

So I was surprised to find the official Blazor templates (dotnet new blazorwasm) have this scoped factory in Program.cs:

builder.Services.AddScoped(sp =>
  new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

I'm even using the IDisposableAnalyzers analyser library that specifically checks for such things, and it warns to replace that line with a single instance.

Why is the template written that way?

CodePudding user response:

This is what I've found.

It has long been recommended to reuse an HttpClient, due to the socket exhaustion problem.

But Blazor's HttpClient doesn't use TCP for connections, it uses the browser's Fetch API instead. And the Fetch API, according to MDN is JavaScript-based:

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

So the original problem doesn't exist, which means we can safely use as many HttpClient instances as we want.

Which is why the Blazor templates use a factory to create multiple instances.

TL;DR: it should be safe.

My only concern is that the above is based on the Blazor docs, but the framework docs for HttpClient do not mention this special behaviour for Blazor. (I wonder how this works - maybe the Blazor SDK has a different implementation for HttpClient than the server SDK?)

If my analysis is wrong, please let me know.

  • Related