title: properly cleanup System.ServiceModel.ServiceHost
body: <p>I'm a little confused about the best way to clean up a ServiceHost.  I became aware of the issue in my code because of the CA1001 warning from the Visual Studio code analyzer suggesting I implement the IDisposable interface for my class.</p>
  
  <p>I have read the discussions on IDisposable and am familiar with the typical use case, but find myself confused in this instance.  What is the proper way to make sure that the ServiceHost is being disposed and possibly satisfy CA1001.  Thanks.</p>
  
  <p>My code looks something like the following:</p>
  
  <p><code></p>
  
  <pre><code>public class MyClass
  {
      private ServiceHost host = null;
  
      public void StartListening(...)
      {
          // make sure we are not already listening for connections
          if (host != null &amp;&amp; host.State != CommunicationState.Closed)
              StopListening();
  
          // create service host instance
          host = new ServiceHostWithData(typeof(ServiceHandler), address);
  
          // do a bunch of configuration stuff on the host
  
          host.Open();
      }
  
      public void StopListening()
      {
          // if we are not closed
          if ((host != null) &amp;&amp; (host.State != CommunicationState.Closed))
          {
              host.Close();
              host = null;
          }
          else // we are null or closed
          {
              host = null; // if it isn't null, and it is already closed, then we set it to null
          }
      }
  }
  </code></pre>
  
  <p></code></p>