Skip to content

Instantly share code, notes, and snippets.

@petermorlion
Last active May 11, 2016 12:14
Show Gist options
  • Save petermorlion/150afe3104baab83af69eb4c0e508594 to your computer and use it in GitHub Desktop.
Save petermorlion/150afe3104baab83af69eb4c0e508594 to your computer and use it in GitHub Desktop.
Simple WCF Proxy
public static class Proxy<T>
{
private static readonly ChannelFactory<T> ChannelFactory = new ChannelFactory<T>("*");
public static void Execute(Action<T> serviceAction)
{
var proxy = (IClientChannel) ChannelFactory.CreateChannel();
var success = false;
try
{
serviceAction((T) proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
public static TResponse Execute<TResponse>(Func<T, TResponse> serviceAction)
{
var response = default(TResponse);
Execute(new Action<T>(service => response = serviceAction(service)));
return response;
}
}
@petermorlion
Copy link
Author

The most simple way of creating a WCF proxy I've seen so far.

Usage:

Proxy<IMyServiceContract>().MyOperation("Hello World");

Remarks

  • The "*" is a wildcard by which the ChannelFactory will search for the endpoint with the correct contract.
  • A ChannelFactory is created per contract type, as it is a static generic field. Creating a ChannelFactory is costly, so done only once per contract. Creating the channel is cheap, so done for each call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment