Last active
December 19, 2015 06:09
-
-
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 :/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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