WCF Using Extension Method


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



Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// When calling a WCF service it is not possible to use a using(...) statement to close
  3. /// the connection after the service call. A call to Dispose may cause an exception
  4. /// which is against MS recommendation. As such when calling a WCF Service you can
  5. /// us the Using method to correctly close the connection after your request or requests.
  6. ///
  7. /// <remarks>This can be used with the following code <br/>
  8. /// <code>
  9. /// IMyService service = new MyService(); // Gets a proxy to WCF service
  10. /// service.Using(()=>
  11. /// {
  12. /// service.DoSomthing();
  13. /// service.DoSomethingElse("Hello World");
  14. /// Console.WriteLine();
  15. /// });
  16. /// </code>
  17. /// </remarks>
  18. /// </summary>
  19. /// <param name="service">The IService instance you wish will close after invocation</param>
  20. /// <param name="action">The Action delegate to execute before the service is closed.</param>
  21. public static void Using(this IService service, Action action)
  22. {
  23. ICommunicationObject communicationObject = service as ICommunicationObject;
  24. try
  25. {
  26. action();
  27. service.SafeDispose();
  28. }
  29. catch (CommunicationException cex)
  30. {
  31. Log.Error(String.Format("CommunicationException occured calling service method on {0}", service.GetType().Name), cex);
  32.  
  33. if (communicationObject != null)
  34. communicationObject.Abort();
  35. throw;
  36. }
  37. catch (TimeoutException tex)
  38. {
  39. Log.Error(String.Format("TimeoutException occured calling service method on {0}", service.GetType().Name), tex);
  40.  
  41. if (communicationObject != null)
  42. communicationObject.Abort();
  43. throw;
  44. }
  45. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.