Dibzmania
Dibzmania

Reputation: 1994

Using static HttpClient vs a different HTTPClient for each set of Endpoint

So my app involves a lot of network calls (probably connecting to 10 different servers) and fetching data. From couple of articles that I have read, reusing a HTTPClient instance is suggested as it prevents wastage of resources (sockets and such). But I am finding it tad difficult to design a module around a static HTTPClient which is extensible and robust. All my server connections needs different sets of headers, query parameters and such. Would I be better off using a one HTTPClient per server/endpoint model.

Upvotes: 3

Views: 760

Answers (1)

Pedro Fernandes
Pedro Fernandes

Reputation: 376

It's easier if you create a HttpClient instance for each server.

You can create a singleton class, as a wrapper for static httpClient and pass them with your Dependency Injection mechanism:

public class ServerAClient {
  private HttpClient _client;
  private static object _locker = new object();

  public static HttpClient GetInstance() {
    if (_client == null) {
      lock (_locker) {
        // create your httpclient here
        _client = instance;
      }
    }

    return _client;
  }
}

public class MyController : Controller {
  private readonly ServerAClient _aclient;
  public MyController(ServerAClient Aclient) {
    _aclient = Aclient;
  }

  public IHttpAction Index() {
    ...
   _aclient.DoSomething();
  }
}

Upvotes: 2

Related Questions