In my one of the .net core project I have to call REST apis to send some data to clients. There are always more than 9-10 clients with different apis having their own domain and custom headers. If I will create HttpClient object each time it will hamper performance since each time new TCP connection will be create and closed. If I will create single HttpClient object using singleton designing pattern then same base url and default header will be used for each client. Can any one suggest a way to solve this problem. I do not wants to go and create new HttpClient every time new client api comes for integration.
Asked
Active
Viewed 1,823 times
3
-
We can help you sort out your code if you paste it in a fiddle? – Brunis Jan 07 '18 at 07:34
-
I have still not written actual code. But this is sample which i was planning to use. Here url can be api of any client public Output CallApi(string url) { var _httpClient = SingletonHttpClient.Instance; if(_httpClient != null) { using (var response = _httpClient.GetAsync(url).Result) { return response.Content.ConvertToObject – Rakesh Jan 07 '18 at 07:49
-
@ToddMenier Thanks. You have given very good suggestion – Rakesh Jan 23 '18 at 04:19
1 Answers
3
If you're calling 9-10 different APIs, where client-level things like default headers could come in handy, then 9-10 static HttpClient
instances is optimal. If coding 9-10 instances feels a little messy/repetitive, you could wrap them in a dictionary object, specifically a ConcurrentDictionary will help keep instantiation both lazy and thread-safe. Something like this should work:
public static class HttpClientManager
{
private static ConcurrentDictionary<string, HttpClient> _clients =
new ConcurrentDictionary<string, HttpClient>();
public static HttpClient Get(string baseUrl)
{
return _clients.GetOrAdd(baseUrl, _ =>
new HttpClient { BaseAddress = new Uri(baseUrl) });
}
}
Then it's just HttpClientManager.Get(baseUrl)
whenever you need to use one.

Todd Menier
- 37,557
- 17
- 150
- 173