Dispose of Injected HttpClient

asp.net-mvc-4, asp.net-web-api, dependency-injection, dotnet-httpclient, structuremap

Solution

Disposing HttpClient cleans up any active Cancellation tokens and any partially complete requests/responses. Under most normal scenarios disposing it will not be essential, although by convention you should. Be aware though that disposing HttpClient will forcibly close the TCP connection.

If your MVC application is making lots of calls to the same server, it might be worth holding onto the HttpClient instance across requests and reusing it. That will avoid you having to re-setup the default request headers each time and it will allow the reuse of the TCP connection.

Problem

Our MVC application calls a WebAPI action using HttpClient. I decided to inject the HttpClient using StructureMap and override dispose in the controller ``` public HomeController(HttpClient httpClient) { _httpClient = httpClient; } protected override void Dispose(bool disposing) { if (disposing && _httpClient != null) { _httpClient.Dispose(); } base.Dispose(disposing); } ``` The StructureMap ObjectInitialize basically looks like this.. ``` x.For<HttpClient>().Use(() => new HttpClient() { BaseAddress = "my/uri/"}); ``` When I build this, CodeAnalysis complains `"Dispose objects before losing scope"`and points to the IoC code. Can I Suppress that, or where do I need to dispose of the HttpClient? I also tried ``` protected void Application_EndRequest(object sender, EventArgs e) { ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects(); } ``` But I still get that rule violation.

Original source