Quick question, but is it best practice to wrap a service proxy class in a using statement? Meaning, in VS, we generated a proxy for a WCF service. For the service class, should it be wrapped in using? I don't believe it implements IDisposable and there is no Dispose() method. Thanks.
Asked
Active
Viewed 1,550 times
1 Answers
4
Although proxies generated by Service Reference and svcutil.exe do implement IDisposable
, in general it is not a best practice to wrap them in a using
block; instead favor explicit open and closing.
Why? Well, the problem is that the Dispose
method calls Close
, which can throw in various circumstances, most prominently if the channel is in a Faulted state. In general this is bad, but if this happens during a finally block because you let a fault exception bubble up, it could swallow the original fault exception in favor of the Close
exception, effectively losing the original exception.

Randolpho
- 55,384
- 17
- 145
- 179
-
Usually, I don't explicitly open and close. I usually initialize the service and invoke methods on it - never actually closing upon completion. I see this a lot too. Bad practice? – Ryan Peters Sep 21 '10 at 15:26
-
@Ryan Peters: if you're using a `using` block, that wouldn't be bad practice, other than the issue I mentioned. But you should always close your channel when you're not using it, either explicitly or implicitly. Explicitly *opening* the channel, on the other hand, isn't always necessary, as the first operation call on the proxy will always open the channel. – Randolpho Sep 21 '10 at 15:50