Use a static instance for default HttpClient
#1919
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
r? @brandur-stripe @richardm-stripe
cc @stripe/api-libraries
Update
Stripe.SystemNetHttpClient
to use a static instance ofSystem.Net.HttpClient
when no HTTP client is passed to the constructor. This means that multiple clients will share the same instance ofSystem.Net.HttpClient
.This is what Microsoft advises in https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client#create-and-initialize-httpclient:
This is thread-safe. The only method we're using is
SendAsync
, which is explicitly listed as thread-safe in the documentation: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?redirectedfrom=MSDN&view=netframework-4.8#remarks.The default instance is wrapped in a
Lazy<>
initializer, so it's only initialized the first time it's needed (to avoid initializing it if it's never used, e.g. because the user is always supplying their own instance).It's difficult to write a test for this because
httpClient
is private, but I temporarily bumped its visibility and verified that this test passed:Fixes #1918.