Clean Up WCF Clients : The Right Way

As I've done more and more WCF work recently, I've noticed an intermittent problem running my unit tests.

The host seemingly hangs for no obvious reason.  Eventually the connection times out and produces the following in the service log:

System.ServiceModel.CommunicationObjectAbortedException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Stopping the host and client and re-running the test allows it to pass without issue. 

The problem is related to the way I managed my WCF channels and client proxies.  In my code I make use of the ChannelFactory object to create my wcf channels dynamically from my configuration information, like the following:

   #region IdentityService Proxy
    private static IIdentityService \_identitySvc;
    private static IIdentityService identitySvc
    {
        get
        {
            if (\_identitySvc == null)
            {
                var factory = new ChannelFactory<IIdentityService>("IdentityService");
                \_identitySvc = factory.CreateChannel();
            }
            return \_identitySvc;
        }

    }
    #endregion

The client proxy produced implements the typed interface "IIdentityService" in the above example. It natively supports no operations for channel management and cleanup. However, failing to clean up the client proxy may cause channel timeouts and resource blocking on the server. So channel cleanup is important, but if its not implemented in the client proxy, how do you manage it?

The secret lies in the casting.  The transparent proxy produced implements a number of useful interfaces.  For our purposes we care about IDisposable and IClientChannel. When we're done with the proxy,  we must close the channel and dispose of it.  I've seen some examples like this:

using (IClientChannel client = (IClientChannel)channelFactory.CreateChannel()) { IIdentityService proxy = (IIdentityService)client; }

This is Bad. Yes, you are disposing of the channel resource, but you haven't closed the wcf channel, you've only disposed of your handle to it. You must explicitly call close then dispose on the proxy like so:

        if (\_identitySvc != null)
         {
             ((IClientChannel)\_identitySvc).Close();
             ((IDisposable)\_identitySvc).Dispose();
             \_identitySvc = null;
         }

Optionally, since IClientChannel implements IDisposable, you could call ((IClientChannel) proxy).Dispose().  If you prefer, and your design allows, you can still use the using statement, just be sure to add try/catch blocks and call the close() method on the casted proxy before the closing brace. I tend to have static references to my proxy classes so I have to explicitly call close() and dispose() when I complete my WCF operation.

Now that I'm properly cleaning up my proxies, my WCF services run all my tests without hanging.

This article is part of the GWB Archives. Original Author: ChrisD

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.