6

We call several APIs of multiple domains in our project using HttpClient. I am creating a common HttpClient to be used for all these API calls. I am confused between two approaches to implement this:

  1. Create a singleton class for HttpClient and use that for every call by passing API URIs in get/post/put methods.
  2. create a singleton class for HttpClientHandler which will be shared among all HttpClients and create one HtppClient for each domain by setting the BaseAddress property. Now we can call the APIs by passing the relative paths in get/post/put methods.

Which one is the better approach?

Is there any benefit of presetting the BaseAddress? If not, why is this property provided?

ctor
  • 805
  • 1
  • 10
  • 26
  • 1
    Take a look here for an example of `BaseAddress`: https://stackoverflow.com/questions/23438416/why-is-httpclient-baseaddress-not-working – Anderson Pimentel Jan 19 '18 at 10:38

2 Answers2

3

If you choose option 1, the BaseAddress of course should not be used, as you'd keep overwriting it and you'd have to avoid two threads updating it before one of them has had a chance to send its request.

If you choose option 2, you can configure your HttpClient per API once (for instance, read BaseAddress and Timeout from a configuration file). Relative uri's can then be supplied without having to prepend the base address for each request.

Which is better I guess depends on whether you want to be able to configure properties such as Timeout or MaxResponseContentBufferSize for all APIs (option 1) or per API (option 2), I don't have a definitive "this one is better" answer.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
0

How about option 3: One HttpClient instance per API (domain) being called. It's a little easier to implement than option 2, still allows you to use a different set of stateful properties (DefaultRequestHeaders, etc.) per API, and still minimizes the number of open sockets lying around, avoiding this infamous problem. This would be my recommendation.

BaseAddress exists solely so you can use relative URIs instead of absolute URIs for individual requests.

Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • I am not seeing any complexity in passing a common `HttpClientHandler` while creating `HttpClient` in option 2. Am I missing something? – ctor Jan 24 '18 at 06:45
  • @ctor Just that you don't need to deal with a handler explicitly at all. Looking at option 2 again, I think my suggestion is exactly the same, minus the handler singleton. I don't think that gains you anything, unless *I'm* missing something. – Todd Menier Jan 28 '18 at 16:23