Skip to content

Instantly share code, notes, and snippets.

@ewilde
Last active December 11, 2015 17:19
Show Gist options
  • Save ewilde/4633849 to your computer and use it in GitHub Desktop.
Save ewilde/4633849 to your computer and use it in GitHub Desktop.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
/// <summary>
/// Wraps a service client so you can use "using" without worrying of getting
/// your business exception swallowed. Usage:
/// <example>
/// <code>
/// using(var serviceClient = new ServiceClientWrapper&lt;IServiceContract&gt;)
/// {
/// serviceClient.Channel.YourServiceCall(request);
/// }
/// </code>
/// </example>
/// </summary>
/// <typeparam name="TServiceType">The type of the service client type to create.</typeparam>
public class ServiceClientWrapper<TServiceType> : IDisposable
{
/// <summary>
/// The channel factory
/// </summary>
private static ChannelFactory<TServiceType> channelFactory;
/// <summary>
/// The channel
/// </summary>
private readonly TServiceType channel;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceClientWrapper{TServiceType}" /> class.
/// As a default the endpoint that is used is the one named after the contracts full name.
/// </summary>
public ServiceClientWrapper() : this(new Logger())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceClientWrapper{TServiceType}" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
[StructureMap.DefaultConstructor]
public ServiceClientWrapper(ILogger logger) : this(typeof(TServiceType).FullName)
{
this.Logger = logger;
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceClientWrapper{TServiceType}" /> class.
/// </summary>
/// <param name="endpoint">The endpoint.</param>
public ServiceClientWrapper(string endpoint)
{
if (channelFactory == null)
{
channelFactory = new ChannelFactory<TServiceType>(endpoint);
}
this.channel = channelFactory.CreateChannel();
((IChannel)this.channel).Open();
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>
/// The logger.
/// </value>
public ILogger Logger { get; set; }
/// <summary>
/// Gets the channel.
/// </summary>
/// <value>The channel.</value>
public TServiceType Channel
{
get { return this.channel; }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
try
{
((IChannel)this.channel).Close();
}
catch (CommunicationException)
{
((IChannel)this.channel).Abort();
}
catch (TimeoutException)
{
((IChannel)this.channel).Abort();
}
catch (Exception exception)
{
((IChannel)this.channel).Abort();
this.Logger.Error(exception);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment