DotNetAnalyzers / IDisposableAnalyzers

Roslyn analyzers for IDisposable
MIT License
381 stars 26 forks source link

IDISP014 should not activate in Blazor projects #387

Open lonix1 opened 2 years ago

lonix1 commented 2 years ago

The IDISP014 analyser is important ("Use a single instance of HttpClient").

But I'm unsure how to handle it in Blazor projects. The template (dotnet new blazorwasm) creates a Program.cs with:

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

...which of course triggers IDISP014.

How do other people handle this? Do you recommend following the analyser and changing that from a factory to a single instance?

lonix1 commented 2 years ago

I've done some research into this and this is what I've found:

It is recommended to reuse an HttpClient due to the socket exhaustion problem - which is why this analyser exists. :wink:

But in blazor the HttpClient doesn't use TCP for connections, it uses the browser's Fetch API, so the original problem doesn't exist. So we can use as many HttpClient instances as we want.

And that is why the official blazor templates use a factory for creating many instances of HttpClient.

So this is a false positive in Blazor projects.

I recommend this analyser detect whether the code is part of a Blazor project - if so, allow multiple instances. A Blazor project has the Microsoft.NET.Sdk.BlazorWebAssembly SDK in its .csproj.

lonix1 commented 2 years ago

See related StackOverflow post here.