-
Notifications
You must be signed in to change notification settings - Fork 15
DynamicRestClient and disposal
The DynamicRestClient uses Microsoft's HttpClient for communication. Since DynamicRestClient is intended to insulate calling code from the underlying communication client, some thought needs to be given to lifetime management of that client.
An HttpClient instance is intended to be reused across requests to a single base uri. This allows a socket to be kept open, saving the performance overhead of creating, opening and closing the socket. All endpoints created from a root DynamicRestClient will share the same HttpClient instance. When the root instance is Disposed this shared HttpClient is disposed at which point any endpoint created from the root will throw an ObjectDisposedException. Disposing the root indicates that the client is done communicating to that base uri.
It is possible for the http verb invocation methods to return the underlying HttpResponseMessage or Stream by passing one of those types to the request. In this case it is up to the caller to dispose the resonse message or stream. In all other cases, when the response content is deserialized, the HttpResponseMessage is disposed internally.
public async Task ReturnResponseStream()
{
using (dynamic google = new DynamicRestClient("https://www.google.com/"))
using (Stream content = await google.get(typeof(Stream)))
{
Assert.IsNotNull(content);
using (var reader = new StreamReader(content))
{
var s = reader.ReadToEnd();
Assert.IsFalse(string.IsNullOrEmpty(s));
Assert.IsTrue(s.StartsWith("<!doctype html>"));
}
}
}