Handy WCF Techniques
July 13th, 2009
I can’t take credit for this one, but I just had to pass it on. Visual Stuart showed me this neat little trick for safely working with WCF proxies. The problem with WCF is that if the server throws an exception, it faults the channel. This means that basically, you need to shut down the channel before trying to use it again or you will be in a nasty state indeed. Here is a handy little extension method to close down your WCF channels nicely.
public static void SafeClose(this ICommunicationObject proxy){try{proxy.Close();}catch{proxy.Abort();}}
So now you can easily wrap it in a generic to be used with all your proxies, like so:
Kudos to James for this one.
public class SafeProxy<Service> : IDisposable where Service : ICommunicationObject{private readonly Service _proxy;public SafeProxy(Service s){_proxy = s;}public Service Proxy{get { return _proxy; }}public void Dispose(){if (_proxy != null)_proxy.SafeClose();}}
Just use it like this without having to litter your code with try / catch.
using (var proxyVar = new SafeProxy<Proxy>(new Proxy())){proxyVar.MakeAnOperationCall();}
Now, that’s just nifty.


