performance, desposing, and unit testing

Topics: Web Api
Feb 24, 2011 at 3:51 PM

We are using the HttpClient to make REST Calls. We are trying to find the right design for performance,  proper clean up of resources, and unit testing. Most examples that I've seen use the following

 Using (HttpClient http = new HttpClient(""))

http.TransportSettings.Credentials =
    new NetworkCredential("{username}", "{password}");
HttpResponseMessage resp = http.Get("friends_timeline.xml");
The Samples do it a different way and have the HttpResponseMessage being disposed. 
In addition to cleaning up the code correctly. If I had either of these 2 codes in a repository of some sort, I couldn't test it because they would be dependant on HttpClient. 
I know I can mock the HttpClientChannel and will be playing with that.

I'd like to see a real world example of how resource clean up should be done and how Unit Testing can be incorporated.
Feb 25, 2011 at 12:39 AM

A few things.  The sample code you included is based on the old HttpClient from the REST Starter Kit.  The new one does not work quite the same way.

The HttpClient should be disposed.   However, I believe that it is probably a good idea if you keep the HTTPClient open across multiple requests.  I keep it open for the life of my application.  

The HttpResponseMessage does implement IDisposable also, but that is just to ensure the  HTTPContent object gets disposed.  If you use the default behaviour of the HttpClient it uses the HttpCompletion option that causes the response body to be completely buffered on receipt and I believe it closes the response stream immediately.  Therefore, you are left with HttpContent object that is just holding onto managed memory.