I have a class that implements IDisposable according to this pattern because it contains a reference to HttpClient. It looks something like this:
public class CustomServiceClient : IDisposable
{
HttpClient client;
// ...
public ServiceCreatedEntity GetEntity()
{
// ...
}
~CustomServiceClient()
{
this.Dispose(false);
}
private bool disposed = false;
void IDisposable.Dispose()
{
if(!disposed)
{
this.Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
public void Dispose(bool disposing)
{
if(disposing)
{
// dispose managed resources
client.Dispose();
}
// dispose unmanaged resources - this class has none
}
}
public class ServiceCreatedEntity
{
CustomServiceClient client;
public ServiceCreatedEntity(CustomServiceClient client)
{
this.client = client;
}
// some functions that use client
}
I'm wondering if ServiceCreatedEntity
should implement IDisposable and dispose of the CustomServiceClient. I expect that CustomServiceClient
will generally have a longer lifetime than ServiceCreatedEntity
, and I'm worried that a client will dispose of ServiceCreatedEntity
and be confused as to why their CustomServiceClient
has been disposed of as well. Any tips would be greatly appreciated!