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
:
using (var client = new SomeWCFServiceClient()) { //Do something with the client }
But, as noted in this MSDN article, wrapping a WCF client in a using
block could mask any errors that result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose()
is called, the client's Close()
method fires, but throws an error because it's in a faulted state. The original exception is then masked by the second exception. Not good.
The suggested workaround in the MSDN article is to completely avoid using a using
block, and to instead instantiate your clients and use them something like this:
try { ... client.Close(); } catch (CommunicationException e) { ... client.Abort(); } catch (TimeoutException e) { ... client.Abort(); } catch (Exception e) { ... client.Abort(); throw; }
Compared to the using
block, I think that's ugly. And a lot of code to write each time you need a client.
Luckily, I found a few other workarounds, such as this one on the (now defunct) IServiceOriented blog. You start with:
public delegate void UseServiceDelegate<T>(T proxy); public static class Service<T> { public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); public static void Use(UseServiceDelegate<T> codeBlock) { IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel(); bool success = false; try { codeBlock((T)proxy); proxy.Close(); success = true; } finally { if (!success) { proxy.Abort(); } } } }
Which then allows:
Service<IOrderService>.Use(orderService => { orderService.PlaceOrder(request); });
That's not bad, but I don't think it's as expressive and easily understandable as the using
block.
The workaround I'm currently trying to use I first read about on blog.davidbarret.net. Basically, you override the client's Dispose()
method wherever you use it. Something like:
public partial class SomeWCFServiceClient : IDisposable { void IDisposable.Dispose() { if (this.State == CommunicationState.Faulted) { this.Abort(); } else { this.Close(); } } }
This appears to be able to allow the using
block again without the danger of masking a faulted state exception.
So, are there any other gotchas I have to look out for using these workarounds? Has anybody come up with anything better?
Using FaultExceptionFault exceptions are exceptions that are thrown by a WCF service when an exception occurs at runtime -- such exceptions are typically used to transmit untyped fault data to the service consumers.
Dispose() unconditionally calls Close() . This will try to make a graceful shutdown of the communications channel with the server. If the channel is in a faulted state this is not allowed and an exception is thrown. The correct thing to do in that case is to call Abort() instead.
WCF allow us to give multiple base addresses for each type of protocol. And at the run time corresponding endpoint will take the base address. So you can expose IService1 on multiple EndPoint with more than one binding as below.
Actually, although I blogged (see Luke's answer), I think this is better than my IDisposable wrapper. Typical code:
Service<IOrderService>.Use(orderService=> { orderService.PlaceOrder(request); });
(edit per comments)
Since Use
returns void, the easiest way to handle return values is via a captured variable:
int newOrderId = 0; // need a value for definite assignment Service<IOrderService>.Use(orderService=> { newOrderId = orderService.PlaceOrder(request); }); Console.WriteLine(newOrderId); // should be updated
Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.
So, to get around this, I've employed a solution that mixes the best of both worlds.
void IDisposable.Dispose() { bool success = false; try { if (State != CommunicationState.Faulted) { Close(); success = true; } } finally { if (!success) Abort(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With