Dogs Chasing Squirrels

A software development blog

Fault-safe WCF Proxy Generator


In WCF, clients connect to servers using channels that implement a particular service contract interface.  This ordinarily works very well – until something throws an exception.  Let’s say you’re a client, you have some channel object you can cast as IWhatever and you can make calls on its methods.

this._factory = new ChannelFactory<IMathContract>( endpoint );

this._channel = this._factory.CreateChannel();

int c = this._channel.Add( a, b );

If one of those methods throws an error, the channel will become faulted and every subsequent call will throw an exception like “The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.”.  What you have to do now is abort and recreate the channel.  But this error could happen anywhere.  So what we usually do is build a proxy.  The proxy wraps the channel, implementing all the interface’s methods, and aborts the channel if any of these calls throw an exception.

 public int Add( int a, int b ) {
    try {
         return this.GetChannel().Add( a, b );
     } catch ( Exception ) {

Writing these proxies is tedious, so I’ve created a utility that uses IL generation to dynamically generate a proxy given a service contract.

IMathContract channel = FaultSafeProxyEmitter<IMathContract>.Create( "MockEndpoint" );

This creates a fault-tolerant channel that will abort and reset if an exception is thrown.  The channel will never remain in the Faulted state.  The channel also implements IDisposable to properly close the underlying channel when complete.

The code is up on github.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: