title: Unit Testing a WCF Client
body: <p>I am working with code that currently does not use any dependency injection, and makes multiple service calls through a WCF client.</p>
  
  <pre><code>public class MyClass
  {
      public void Method()
      {
          try
          {
              ServiceClient client = new ServiceClient();
              client.Operation1();
          }
          catch(Exception ex)
          {
              // Handle Exception
          }
          finally
          {
              client = null;
          }
  
          try
          {
              ServiceClient client = new ServiceClient();
              client.Operation2();
          }
          catch(Exception ex)
          {
              // Handle Exception
          }
          finally
          {
              client = null;
          }
      }
  }
  </code></pre>
  
  <p>My goal is to make this code unit-testable through the use of dependency injection. My first thought was to simply pass an instance of the service client to the class constructor. Then in my unit tests, I can create a mock client for testing purposes that does not make actual requests to the web service.</p>
  
  <pre><code>public class MyClass
  {
      IServiceClient client;
  
      public MyClass(IServiceClient client)
      {
          this.client = client;
      }
  
      public void Method()
      {
          try
          {
              client.Operation1();
          }
          catch(Exception ex)
          {
              // Handle Exception
          } 
  
          try
          {
              client.Operation2();
          }
  
          catch(Exception ex)
          {
              // Handle Exception
          }
      }
  }
  </code></pre>
  
  <p>However, I realized that this changes the code in a way that affects its original behavior, based on the information from this question: <a href="https://stackoverflow.com/questions/811142/reuse-a-client-class-in-wcf-after-it-is-faulted">Reuse a client class in WCF after it is faulted</a></p>
  
  <p>In the original code, if the call to Operation1 fails and the client is put in a faulted state, a new instance of ServiceClient is created, and Operation2 will still be called.
  In the updated code, if the call to Operation1 fails, the same client is reused to call Operation2, but this call will fail if the client is in a faulted state.</p>
  
  <p>Is it possible to create a new instance of the client while keeping the dependency injection pattern? I realize that reflection can be used to instantiate a class from a string, but I feel like reflection isn't the right way to go about this.</p>