Fixing the WCF Proxy

If you’ve been programming WCF for a while, you’re probably used to the convenience of using the proxy class generated by svcutil.exe when you add a Service Reference to a Visual Studio project. You’re also probably used to creating the proxy within a using block, so that its Dispose method is called and cleanup can take place in a robust fashion.

However, you may not be aware that closing the proxy at the end of the using block could result in an exception (for example, a Timeout or Communication exception) and that you should catch this exception and call Abort on the client channel, as described in this MSDN topic: http://msdn.microsoft.com/en-us/library/aa355056(VS.85).aspx.

using (MyServiceClient proxy = new MyServiceClient())
{
    proxy.SomeOperation();
} // Could throw an exception here

To remedy this, I wrote a code snippet that creates a partial class to extend the generated proxy class by implementing IDisposable and properly handling the cleanup. Although there are other approaches you could take, what I like about the code snippet is that it doesn’t require you to change the code that creates and uses the proxy. Here’s the code that the snippet produces:

namespace Client.MyService
{
    public partial class MyServiceClient : IDisposable
    {
        bool disposed;

        public void Dispose()
        {
            if (!disposed)
            {
                CloseChannel();
            }
            disposed = true;
        }

        void CloseChannel()
        {
            try
            {
                if (base.InnerChannel.State
                    != CommunicationState.Closed)
                {
                    this.InnerChannel.Close();
                }
            }
            catch
            {
                this.InnerChannel.Abort();
            }
        }
    }
}

The code snippet has placeholders for both the namespace name and the class name, which reflect what you specified when adding the Service Reference. You can download the code snippet here. To install it, place it in the My Code Snippets folder: …\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets. Enjoy.

About Tony Sneed

Sr. Software Solutions Architect, Hilti Global Application Software
This entry was posted in Technical. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.