Skip to content

Instantly share code, notes, and snippets.

@emertechie
Last active December 19, 2015 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emertechie/5909512 to your computer and use it in GitHub Desktop.
Save emertechie/5909512 to your computer and use it in GitHub Desktop.
WcfClientWrapper. Based on code picked up from http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue Creating gist so I don't have to recreate this everytime I do any WCF :/
public static class WcfClientWrapper
{
public static WcfClientWrapper<TClientInterface> Create<TClientInterface>(ChannelFactory<TClientInterface> channelFactory)
{
return new WcfClientWrapper<TClientInterface>(channelFactory);
}
}
public class WcfClientWrapper<TClientInterface> : IDisposable
{
private readonly ChannelFactory<TClientInterface> _channelFactory;
private Lazy<IClientChannel> _clientChannel;
public WcfClientWrapper(ChannelFactory<TClientInterface> channelFactory)
{
_channelFactory = channelFactory;
_clientChannel = CreateLazyClientChannel(_channelFactory);
}
public void Invoke(Action<TClientInterface> clientAction)
{
Invoke(client =>
{
clientAction(client);
return (object)null;
});
}
public TRet Invoke<TRet>(Func<TClientInterface, TRet> clientFunc)
{
bool success = false;
try
{
var retVal = clientFunc((TClientInterface)_clientChannel.Value);
success = true;
return retVal;
}
finally
{
if (!success)
{
_clientChannel.Value.Abort();
_clientChannel = CreateLazyClientChannel(_channelFactory);
}
}
}
private static Lazy<IClientChannel> CreateLazyClientChannel(ChannelFactory<TClientInterface> channelFactory)
{
return new Lazy<IClientChannel>(() => (IClientChannel)channelFactory.CreateChannel());
}
public void Dispose()
{
if (_clientChannel.IsValueCreated)
{
_clientChannel.Value.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment