Some time ago I posted a rant about how I disliked the failure model for Windows Communication Foundation ServiceHosts. Turns out I was only partly right.

The thing is, the ServiceHost behavior is not quite as I described. When it fails it actually does throw a useful exception, however, you need to be aware of how to correctly close the host in case of failures.

What happens is that if you call Close() on the ServiceHost after it threw an exception (i.e. it was in the Faulted state), you'll get a new exception, this time the dreaded CommunicationObjectFaultedException, which "hides" the original exception, thus giving origin to my earlier rant.

I can live with this, and up to a point, it makes sense. What I do dislike is the fact that the model is certainly "broken" in my opinion because based on the behavior above, I can tell that objects such as ServiceHost should've never implemented IDisposable in the first place. The reason is simple: The standard model for IDisposable is: Call it as soon as you're done with the resource, even in fault scenarios. That's why the using block in C# is implemented as a try{}/finally{} block.

The "don't call Close()/Dispose() if faulted" behavior that ServiceHost requires does not work well with IDisposable; it demands a behavior different from the standard IDisposable pattern. Thus, ServiceHost should not have implemented IDisposable, because it misleads developers into thinking that they should use the standard IDisposable/using pattern with it, which, as I mentioned, causes a lot of grief.

Tomas Restrepo

Software developer located in Colombia. Sr. PFE at Microsoft.