Implement IDisposable

232 Views Asked by At

I have a following class:

public class MyClass : IDisposable
{
   private WebServiceHost m_WebServiceHost;
   // Members
   public void Dispose()
   {
            m_WebServiceHost // how do I dispose this object?
   }
}

WebServiceHost implements IDisposable, but it has no Dispose method.

How do I implement Dispose()?

2

There are 2 best solutions below

0
On

Given that it uses explicit interface implementation, it's not clear to me that they want you to, but you can:

public class MyClass : IDisposable
{
   private WebServiceHost m_WebServiceHost;
   // Members
   public void Dispose()
   {
            ((IDisposable)m_WebServiceHost).Dispose();
   }
}

I would guess that they'd prefer you just to call Close() on it, but I can't back that up from documentation yet.

8
On

Do it like this:

public class MyClass : IDisposable
{
   private WebServiceHost m_WebServiceHost;

   // Often you have to override Dispose method 
   protected virtual void Dispose(Boolean disposing) {
     if (disposing) {
       // It looks that WebServiceHost implements IDisposable explicitly
       IDisposable disp = m_WebServiceHost as IDisposable;

       if (!Object.RefrenceEquals(null, disp))
         disp.Dispose();

       // May be useful when debugging
       disp = null;       
     }
   }

   // Members
   public void Dispose()
   {
     Dispose(true);
     GC.SuppressFinalize(this);
   }
}