graphql-dotnet / graphql-dotnet/graphql-client

Socket Exhaustion: IHttpClientFactory should be used instead of HttpClient()

Open
#363 4 comments 2 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
648
Forks
136
PR merge metrics
No merged PRs in 30d

Description

You should not use [`new HttpClient()`](https://github.com/graphql-dotnet/graphql-client/blob/b366e22af112445452440c2c6c1d9978ecef97cb/src/GraphQL.Client/GraphQLHttpClient.cs#L60) in GraphQLHttpClient constructor, because there is known problem with `new HttpClient()` socket exhaustion under heavy server load.

Instead, you should inject 'IHttpClientFactory' and call (for example) `var client = HttpClientFactory.CreateClient(nameof(GraphQLHttpClient))`

I think i can (at least try to) do PR for you, but i fear this is breaking change, because the `GraphQLHttpClient` is not resolved from DI but created by hand (at least README.md show this)

Workaround is to supply `HttpClient` resolved from `IHttpClientFactory` by yourself:

(i am writing this from top of my head, maybe there is typo or two 😄 )
```c#
private readonly IHttpClientFactory _httpClientFactory;

ctor(IHttpClientFactory httpClientFactory){
_httpClientFactory= httpClientFactory;
}

SendSomeGraphQL(string query ... )
{
using var httpClient = _httpClientFactory.CreateClient(nameof(GraphQLHttpClient));
var graphQLClient =
new GraphQLHttpClient(
new GraphQLHttpClientOptions { EndPoint = new Uri("https://api.example.com/graphql") },
new NewtonsoftJsonSerializer(),
httpClient
);
...
}
```

Further reading:

https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.