-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Analyzer to warn against locally scoped HttpClient instance #121
Comments
The docs are only partially accurate there. The real problem comes from not reusing a My initial thinking is along these lines:
There are probably some special cases that we could ignore (such as if the enclosing function is the program's Main entrypoint), but it may just be simpler to suppress the warning using SuppressWarningAttribute in places where the use is valid, as having the suppression will educate readers that this is not a generally acceptable approach, rather it is a valid exception. (I just hope people don't follow the common behavior of disabling the rule or suppressing the warning in cases where the warning is valid). |
Can you please provide a reference to back your assertion that it is really the |
The documentation kind of glosses over the fact that If you look at the implementation of The actual connection and socket management, on all .NET platforms and runtimes that I've looked at, do it in Since the To further validate this, .NET's own |
From https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1:
HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
In .NET Core they have also introduced IHttpClientFactory: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
This is easy to forget as it goes against the normal best practice of creating and disposing an instance of a class when you need it.
Create a analyzer rule to warn against creating an HttpClient instance scoped to a single function or class instance.
The text was updated successfully, but these errors were encountered: