Generic service client base class for WCF
This file contains 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 class ClientWrapperUsage | |
{ | |
public static void main(string[] args) | |
{ | |
using(var clientWrapper = new ServiceClientWrapper<ServiceType>()) | |
{ | |
var response = clientWrapper.Channel.ServiceCall(); | |
} | |
} | |
} |
This file contains 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
/// <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<IServiceContract>) | |
/// { | |
/// 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<ServiceType>"/> 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<ServiceType>"/> 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