Posted By

rstokoe on 02/03/12


Tagged

wcfextension methodc#connectionsclientproxiesproxy


Versions (?)

Extension Method to Correctly Close WCF Connections When Faults Occur


 / Published in: C#
 

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

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

  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. }

Report this snippet  

You need to login to post a comment.