Disposing a WCF proxy using an extension method
A while back I read a blog post by Dan Rigsby about why you should not use C# using statements on a WCF service proxy class even though it implements IDisposable. Basically it comes down to the Dispose() method calls Close() which can throw an exception preventing the service proxy from being disposed properly. The solution by Dan Rigsby involving a wrapper class and another solution by Erwyn van der Meer (which provides a helper class that you can derive from) both allow you to use the using statement and still properly dispose of the proxy.
I wrote an extension method below will dispose a service proxy properly, but it doesn’t require you to change that proxy in any way. By providing an extension method around ICommunicationObject, any WCF class that dervives from it (ClientBase, ServiceHostBase, etc.) will have this method available as well.
public static class ICommunicationObjectExtensions
{
public static void TryCloseOrAbort(this ICommunicationObject obj)
{
if (obj != null)
{
if (obj.State != CommunicationState.Faulted &&
obj.State != CommunicationState.Closed)
{
try { obj.Close(); }
catch (CommunicationObjectFaultedException)
{ obj.Abort(); }
catch (TimeoutException)
{ obj.Abort(); }
catch (Exception)
{
obj.Abort();
throw;
}
}
else
obj.Abort();
}
}
}
With that method in place, all you you have to do is call TryCloseOrAbort() in a try-finally block to make sure it is called even if an exception is thrown.
// Example usage:
// assume MyServiceClient is a WCF service proxy class
var client = new MyServiceClient();
try { client.MyServiceMethod(); }
finally { client.TryCloseOrAbort(); }