I have a HttpClientWrapper class to bring unit testability over my classes which are making HttpCalls.
This class is injected via IoC, and acts as a singleton. Because I would like to use same HttpClient instance over and over again without disposing it.
Do HttpClient and HttpClientHandler have to be disposed?
public class HttpClientWrapper : IHttpClientWrapper
{
readonly HttpClient _client;
public HttpClientWrapper()
{
_client = new HttpClient();
}
public Uri BaseAddress
{
get { return _client.BaseAddress; }
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message)
{
Task<HttpResponseMessage> sendAsync = _client.SendAsync(message);
return sendAsync;
}
}
Following clears the warning naturally.
public class HttpClientWrapper : IHttpClientWrapper, IDisposable
{
readonly HttpClient _client;
public HttpClientWrapper()
{
_client = new HttpClient();
}
public Uri BaseAddress
{
get { return _client.BaseAddress; }
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message)
{
Task<HttpResponseMessage> sendAsync = _client.SendAsync(message);
return sendAsync;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_client != null)
{
_client.Dispose();
}
}
}
When I run code analysis, I am receiving following warning from IDE.
CA1001 Types that own disposable fields should be disposable Implement IDisposable on 'HttpClientWrapper' because it creates members of the following IDisposable types: 'HttpClient'. If 'HttpClientWrapper' has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers.
So am I missing something here? Since I would like to keep only one instance of HttpClient and would like not to dispose it, can I safely surpress the warning?
Does second version of class implementation makes sense?