I like instantiating my WCF service clients within a using
block as it\'s pretty much the standard way to use resources that implement IDisposable
:
I'd like to add implementation of Service from Marc Gravell's answer for case of using ServiceClient instead of ChannelFactory.
public interface IServiceConnector
{
void Connect(Action clientUsage);
TResult Connect(Func channelUsage);
}
internal class ServiceConnector : IServiceConnector
where TServiceInterface : class where TService : ClientBase, TServiceInterface, new()
{
public TResult Connect(Func channelUsage)
{
var result = default(TResult);
Connect(channel =>
{
result = channelUsage(channel);
});
return result;
}
public void Connect(Action clientUsage)
{
if (clientUsage == null)
{
throw new ArgumentNullException("clientUsage");
}
var isChanneldClosed = false;
var client = new TService();
try
{
clientUsage(client);
client.Close();
isChanneldClosed = true;
}
finally
{
if (!isChanneldClosed)
{
client.Abort();
}
}
}
}