Skip to content

Disposable wrapper for WCF clients

When a WCF client calls a service and the call throws an exception (no FaultException, that's fine), then calling Close() or Dispose() on that client will throw another Exception because the client is in the faulted state. The correct way to "dispose" or cleanup a faulted client is to call Abort(). This means that we can't embed the WCF client in a using-statement because that will always dispose the client.

The correct way would be

ServiceClient myClient = new ServiceClient();
try
{
myClient.DoSomething();
myClient.Close();
}
catch
{
myClient.Abort();
// error handling or throw;
}

Because some of my projects use a lot of WCF calls, this pattern is too tedious for me. Instead I wrote a simple wrapper:

using System;
using System.ServiceModel;

public class GenericProxy<T> : ClientBase<T>, IDisposable
where T : class
{
public GenericProxy()
: base()
{
}

void IDisposable.Dispose()
{
if (State == CommunicationState.Faulted)
Abort();
else
Close();
}

public T Service
{
get
{
return Channel;
}
}
}

The only drawback is that instead of writing myClient.DoSomething() now I have to write myClient.Channel.DoSomething():

using (GenericProxy<IService> myClient = new GenericProxy<IService>())
{
myClient.Channel.DoSomething();
}

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options