Reputation: 875
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:
HttpClient
and use that for every call by passing API URIs in get/post/put
methods.HttpClientHandler
which will be shared among all HttpClient
s 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?
Upvotes: 7
Views: 3085
Reputation: 39349
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.
Upvotes: 0
Reputation: 26446
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.
Upvotes: 3