WCF - Exception handling and disposing channels

02.06.2010 01:36Comments
Looking for a way to avoid duplicating the Exception handling and disposal code of WCF channels, I ran into this post which gives an interesting approach. However I needed a way make return values more generic, so here is my little tunning.

The code

public static class Service<T> { public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); public static TResult Use<TResult>(Func<T, TResult> codeBlock) { var proxy = (IClientChannel)_channelFactory.CreateChannel(); bool success = false; try { var result = codeBlock((T)proxy); proxy.Close(); success = true; return result; } catch(..) { //Exception handling here. } finally { if (!success) { proxy.Abort(); } } } }

How to use it

//Expose this to your system through an interface for proper loosely coupling. public bool IsUsernameAvailable(string name) { return Service<IUserManagementService>.Use<bool>(proxy => proxy.IsUsernameAvailable(name)); } For those of you using disposable Clients (clients that implement IDisposable) you can use a very similar approach, just wrap the code inside the Use method with a using statement.

With disposable clients

public static class Service<T> where T : IDisposable, new() { public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); public static TResult Use<TResult>(Func<T, TResult> codeBlock) { using (var proxy = new T()) { bool success = false; try { var result = codeBlock((T)proxy); proxy.Close(); success = true; return result; } catch(..) { //Exception handling here. } } } }

comments powered by Disqus