Skip to content
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

Use a static instance for default HttpClient #1919

Merged
merged 1 commit into from
Feb 12, 2020
Merged

Conversation

ob-stripe
Copy link
Contributor

r? @brandur-stripe @richardm-stripe
cc @stripe/api-libraries

Update Stripe.SystemNetHttpClient to use a static instance of System.Net.HttpClient when no HTTP client is passed to the constructor. This means that multiple clients will share the same instance of System.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:

HttpClient is intended to be instantiated once and reused throughout the life of an application.

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:

var client1 = new SystemNetHttpClient();
var client2 = new SystemNetHttpClient();

Assert.NotSame(client1, client2);
Assert.Same(client1.HttpClient, client2.HttpClient);

Fixes #1918.

Copy link
Contributor

@brandur-stripe brandur-stripe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Nice extra rigor :)

LGTM.

@ob-stripe
Copy link
Contributor Author

Thanks Brandur!

@ob-stripe ob-stripe merged commit 10e41f7 into master Feb 12, 2020
@ob-stripe ob-stripe deleted the ob-static-http-client branch February 12, 2020 01:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Following best-practices for HttpClient
4 participants