WCF Async without proxies

time to read 2 min | 225 words

I don't like generated proxies for web services, they are generally ugly and not fun to work with. However, up until recently I believed that I had to deal with them if I wanted to use the async operations for web services. As it turn out, I was wrong.

We can actually define an WCF service interface like this:

[ServiceContract]
public interface IAsyncBus
{
	[OperationContract(AsyncPattern = true)]
	IAsyncResult BeginProcess(IMessage[] request, AsyncCallback callback, object asyncState);

	IMessage[] EndProcess(IAsyncResult result);
}

Now you can work with it using:

IAsyncBus bus = new ChannelFactory<IAsyncBus>().CreateChannel();
ar = bus.BeginProcess(...);
//do work
bus.EndProcess(ar);

The problem with that is that on the server side, I also have to do things in an async manner. This is sometimes appropriate, but it tends to be a major PITA for a lot of things.

As it turn out, we can solve the issue with aliasing. In the interface dll, we can define:

[ServiceContract]
public interface IBus
{
	[OperationContract]
	IMessage[] Process(IMessage[] request);
}

[ServiceContract(Name="IBus")]
public interface IAsyncBus
{
	[OperationContract(AsyncPattern = true)]
	IAsyncResult BeginProcess(IMessage[] request, AsyncCallback callback, object asyncState);
	IMessage[] EndProcess(IAsyncResult result);
}

Now, you can create an instance of IAsyncBus to communicate with IBus directory. On the server side, we implement IBus, and handle the message in a synchronous manner. Easy, simple, and doesn't require any proxies :-)