Extension Method to Correctly Close WCF Connections When Faults Occur


/ Published in: C#
Save to your folder(s)

Shows how to generically handle fault exceptions in WCF Services which prevent you relying on using() {} to dispose of the connection.


Copy this code and paste it in your HTML
  1. namespace WcfChannelExtensions
  2. {
  3. /// <summary>
  4. /// Provides extension methods for WCF Service Channels
  5. /// </summary>
  6. public static class WcfChannelExtensions
  7. {
  8. /// <summary>
  9. /// Make WCF service calls without needing to worry about disposing of underlying connection when Faults occur.
  10. /// </summary>
  11. /// <typeparam name="T">The channel</typeparam>
  12. /// <param name="client">The service.</param>
  13. /// <param name="work">Code to execute.</param>
  14. /// <example>new ChannelFactory<IFooContract>().CreateChannel().SafeInvoke(service =>
  15. /// {
  16. /// service.Foo();
  17. /// });</example>
  18. public static void SafeInvoke<T>(this T client, Action<T> work) where T : ICommunicationObject
  19. {
  20. try
  21. {
  22. client.Open();
  23. work(client);
  24. client.Close();
  25. }
  26. catch
  27. {
  28. client.Abort();
  29. throw;
  30. }
  31. }
  32. }
  33. }

URL: http://www.sage.co.uk/devblog

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.