Rakesh
Rakesh

Reputation: 71

How to call multiple client apis using HttpClient in .net and .net core

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.

Upvotes: 3

Views: 2252

Answers (1)

Todd Menier
Todd Menier

Reputation: 39319

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.

Upvotes: 3

Related Questions