Skip to content

Instantly share code, notes, and snippets.

@mastoj
Created December 6, 2010 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastoj/730846 to your computer and use it in GitHub Desktop.
Save mastoj/730846 to your computer and use it in GitHub Desktop.
Generic service client base class for WCF
public class ClientWrapperUsage
{
public static void main(string[] args)
{
using(var clientWrapper = new ServiceClientWrapper<ServiceType>())
{
var response = clientWrapper.Channel.ServiceCall();
}
}
}
/// <summary>
/// Wraps a service client so you can use "using" without worrying of getting
/// your business exception swalloed. Usage:
/// <example>
/// <code>
/// using(var serviceClient = new ServiceClientWrapper&lt;IServiceContract&gt;)
/// {
/// serviceClient.Channel.YourServiceCall(request);
/// }
/// </code>
/// </example>
/// </summary>
/// <typeparam name="ServiceType">The type of the ervice type.</typeparam>
public class ServiceClientWrapper<ServiceType> : IDisposable
{
private ServiceType _channel;
/// <summary>
/// Gets the channel.
/// </summary>
/// <value>The channel.</value>
public ServiceType Channel
{
get { return _channel; }
}
private static ChannelFactory<ServiceType> _channelFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceClientWrapper&lt;ServiceType&gt;"/> class.
/// As a default the endpoint that is used is the one named after the contracts full name.
/// </summary>
public ServiceClientWrapper() : this(typeof(ServiceType).FullName)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="ServiceClientWrapper&lt;ServiceType&gt;"/> class.
/// </summary>
/// <param name="endpoint">The endpoint.</param>
public ServiceClientWrapper(string endpoint)
{
if (_channelFactory == null)
_channelFactory = new ChannelFactory<ServiceType>(endpoint);
_channel = _channelFactory.CreateChannel();
((IChannel)_channel).Open();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
try
{
((IChannel)_channel).Close();
}
catch (CommunicationException e)
{
((IChannel)_channel).Abort();
}
catch (TimeoutException e)
{
((IChannel)_channel).Abort();
}
catch (Exception e)
{
((IChannel)_channel).Abort();
// TODO: Insert logging
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment