I like instantiating my WCF service clients within a using
block as it\'s pretty much the standard way to use resources that implement IDisposable
:
I've finally found some solid steps towards a clean solution to this problem.
This custom tool extends WCFProxyGenerator to provide an exception handling proxy. It generates an additional proxy called
ExceptionHandlingProxy
which inheritsExceptionHandlingProxyBase
- the latter of which implements the meat of the proxy's functionality. The result is that you can choose to use the default proxy that inheritsClientBase
orExceptionHandlingProxy
which encapsulates managing the lifetime of the channel factory and channel. ExceptionHandlingProxy respects your selections in the Add Service Reference dialog with respect to asynchronous methods and collection types.
Codeplex has a project called Exception Handling WCF Proxy Generator. It basically installs a new custom tool to Visual Studio 2008, then use this tool to generate the new service proxy (Add service reference). It has some nice functionality to deal with faulted channels, timeouts and safe disposal. There's an excellent video here called ExceptionHandlingProxyWrapper explaining exactly how this works.
You can safely use the Using
statement again, and if the channel is faulted on any request (TimeoutException or CommunicationException), the Wrapper will re-initialize the faulted channel and retry the query. If that fails then it will call the Abort()
command and dispose of the proxy and rethrow the Exception. If the service throws a FaultException
code it will stop executing, and the proxy will be aborted safely throwing the correct exception as expected.