My Development Blog

My Development experiences

Posts Tagged ‘WCF’

WCF Services – Dispose can cause you problems

Posted by ipwright83 on November 7, 2013

Normally when you’re working with something that implements IDisposable you should always call Dispose() on it. Unfortunately there are a whole bunch of classes that implement IDisposable implicitly. What that means is that you don’t see Dispose in intelli-sense, which makes it quite difficult to check. The general rule is if it’s going to deal with Stream/Connections/GDI/Databases there will probably be a dispose in there somewhere. The simplest way to do this is to wrap the code in a using statement to ensure that Dispose is called even if there is an error.

Once such example of this is the WCFClient. You would normally expect to write something like the following

using(PaymentPortTypeClient client = new PaymentPortTypeClient())
{
    // Do Stuff
}

Unfortunately however for WCF the base class System.ServiceBase.ClientBase can throw an Exception in Dispose if the connection failed to open for any reason. This is a bit of a pain, so instead we need to conditionally dispose depending on the connection state.

A little helper for achieving this:

 ///
/// Use the service safely such that it will correctly dispose itself upon success or failure.
///
/// The delegate to execute safely 
public static void Use<T>(UseServiceDelegate codeBlock) 
{ 
   // Ensure that the factory has been initialized 
   IClientChannel proxy = (IClientChannel)channelFactory.CreateChannel(); 
   bool success = false; 
   try 
   { 
       codeBlock((T)proxy); 
       proxy.Close(); 
       success = true; 
   } 
   finally 
   { 
       if (!success) 
       { 
           proxy.Abort(); 
       } 
   } 
}

At this point assuming you’ve placed the method in a class called Service you can use the following code to safely call the same code that Dispose would on your connection:

Service.Use<PaymentPortType>(proxy =>
{ 
   // Do Stuff
}

Posted in C# | Tagged: , | 2 Comments »