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.
-
We can help you sort out your code if you paste it in a fiddle?Brunis– Brunis2018-01-07 07:34:13 +00:00Commented Jan 7, 2018 at 7: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<Output>().Result; } } return null; }Rakesh– Rakesh2018-01-07 07:49:21 +00:00Commented Jan 7, 2018 at 7:49
-
@ToddMenier Thanks. You have given very good suggestionRakesh– Rakesh2018-01-23 04:19:16 +00:00Commented Jan 23, 2018 at 4:19
Add a comment
|
1 Answer
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.