Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Dec 13, 2012 12:15 PM by priya_marwaha
Dec 03, 2012 09:46 AM|LINK
I have a requirement where my WebAPI based REST service, say SvcA needs to invoke another REST service (SvcB) in order to perform some processing. I've writen a "proxy" class that uses HttpClient to invoke SvcB. What are the best practices for instantiating
an HttpClient in this sscenario?
Initially, I was creating a new instance of HttpClient and invoking SvcB - without disposing HttpClient. I very quickly ran into a "socket buffer full issue" on my web service, since HttpClient wasn't closing the connections (number of connections = numer
of requests made). I then tried to use a single instance of HttpClient to service multiple requests (without disposing the shared HttpClient instance). Although the number of open connections to my server went down (even after all the calls are made), it didn't
go down to zero (until I do an IISReset). I'm now back to instantiating HttpClient for every request, but disposing the instance once the call is complete (I'm using "using" by the way, and not explicitly invoking Dispose on HttpClient).
Is there a better way to do this?
Dec 04, 2012 03:12 AM|LINK
There are some good suggestions for the usage of HttpClient at
Dec 05, 2012 04:39 PM|LINK
Thanks, the link was useful, but didn't have anything specific regarding usage on server. Appreciate your help.
Dec 07, 2012 01:55 PM|LINK
In short, you should instantiate only one HttpClient for the lifetime of your application, if possible, as HttpClient is an expensive class to instantiate. If you use an IoC container, you could set the lifetime to treat the instance as a singleton and inject
that single instance into all of the controllers that use it. If you don't use IoC, you could just stick an instance created in your WebApiConfig into the Configuration instance's Properties property, then retrieve it from the HttpRequestMessage.
HttpClient should be generally stateless and reusable across multiple calls. If your proxy instance is also stateless, then you should be able to do the same with that type.
I hope that helps.
Dec 13, 2012 12:15 PM|LINK
Thanks! Yup, I understood that part but I didn't see much of a different in # of open sockets etc. when I use a single HttpClient versus multiple (that are disposed immediately post the request). Based on the replies on this thread, it looks like it would
be faster to use a singleton though. I'll check it out.