Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of setting `BaseAddress` property of `HttpClient`

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?

like image 498
ctor Avatar asked Jan 19 '18 10:01

ctor


1 Answers

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.

like image 50
C.Evenhuis Avatar answered Oct 23 '22 20:10

C.Evenhuis