Today I would just like to show how to correctly write the code when using a WCF client proxy to call an WCF service.

Firstly you have to create a Service Reference to the service so that the relevant code is generated for the client proxy.

Here is the correct code:

   1: ProductClient client = new ProductClient();
   2: try
   3: {             
   4:    client.Open();
   5:    client.UpdatePrice(10, 100.50);
   6:    client.Close();
   7: }
   8: catch (Exception e)
   9: {
  10:    Assert.Fail(e.Message);
  11: }
  12: finally
  13: {
  14:    if (client.State != CommunicationState.Closed)
  15:    {
  16:       client.Abort();
  17:    }
  18: }

As you can see I first create the ProductClient proxy object and call open. Then the relevant Web method and then close the client proxy channel.

Then I create a catch section to display the relevant details. In the code above I use Assert.Fail() because this code is used in a unit test, but you can but logging in or any other exception handling logic.

The finally section is there to check if the channel has closed successfully otherwise will call abort on the channel. This allows the correct exception details been catch if an exception is raised in the web method or when the channel is closed.

Here is the wrong code (The popular approach):

   1: using(ProductClient client = new ProductClient())
   2: {

   3:     client.UpdatePrice(10, 100.50);
   4: }

So what is wrong with this? Well the problem is that if an exception is raised in the web method UpdatePrice() and an exception is raised in the Close() method of the client proxy channel is closed by the using() statement then the close exception would hide the original exception that is raised by the web method UpdatePrice().

The first code snippet is much clearer and show what really is happening if an exception should be raised. Where the using does make the code smaller and handle the open closing of the client proxy, but could hide the specific details of the original exception.


Categories: , ,