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
:
A wrapper like this would work:
public class ServiceClientWrapper : IDisposable
{
private ServiceType _channel;
public ServiceType Channel
{
get { return _channel; }
}
private static ChannelFactory _channelFactory;
public ServiceClientWrapper()
{
if(_channelFactory == null)
// Given that the endpoint name is the same as FullName of contract.
_channelFactory = new ChannelFactory(typeof(T).FullName);
_channel = _channelFactory.CreateChannel();
((IChannel)_channel).Open();
}
public void Dispose()
{
try
{
((IChannel)_channel).Close();
}
catch (Exception e)
{
((IChannel)_channel).Abort();
// TODO: Insert logging
}
}
}
That should enable you to write code like:
ResponseType response = null;
using(var clientWrapper = new ServiceClientWrapper())
{
var request = ...
response = clientWrapper.Channel.MyServiceCall(request);
}
// Use your response object.
The wrapper could of course catch more exceptions if that is required, but the principle remains the same.