ServiceClientWrapper.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. using Aitex.Core.RT.Log;
  7. using System.Windows;
  8. using Aitex.Core.Utilities;
  9. using System.Threading;
  10. namespace Aitex.Core.WCF
  11. {
  12. public class ServiceClientWrapper<T>
  13. {
  14. ChannelFactory<T> _factory;
  15. T _proxy;
  16. bool _isInError = false;
  17. string _serviceName;
  18. Retry _retryConnect = new Retry();
  19. public ServiceClientWrapper(string endpointConfigurationName, string name)
  20. {
  21. _serviceName = name;
  22. try
  23. {
  24. _factory = new ChannelFactory<T>(endpointConfigurationName);
  25. }
  26. catch (Exception ex)
  27. {
  28. MessageBox.Show("不能创建Service " + name + ",检查配置:" + endpointConfigurationName);
  29. LOG.Error("不能创建Service "+name+",检查配置:"+endpointConfigurationName, ex);
  30. }
  31. }
  32. public ServiceClientWrapper(string endpointConfigurationName, string name, EndpointAddress address)
  33. {
  34. _serviceName = name;
  35. try
  36. {
  37. _factory = new ChannelFactory<T>(endpointConfigurationName, address);
  38. }
  39. catch (Exception ex)
  40. {
  41. MessageBox.Show("不能创建Service " + name + ",检查配置:" + endpointConfigurationName);
  42. LOG.Error("不能创建Service " + name + ",检查配置:" + endpointConfigurationName, ex);
  43. }
  44. }
  45. public void Invoke(Action<T> action)
  46. {
  47. if (_factory == null)
  48. return;
  49. if (_proxy == null)
  50. {
  51. _proxy = _factory.CreateChannel();
  52. }
  53. for (int i = 0; i < 2; i++)
  54. {
  55. if (Do(action))
  56. break;
  57. Thread.Sleep(10);
  58. }
  59. }
  60. bool Do(Action<T> action)
  61. {
  62. if (_proxy != null && ((IClientChannel)_proxy).State == CommunicationState.Faulted)
  63. {
  64. ((IClientChannel)_proxy).Abort();
  65. _proxy = _factory.CreateChannel();
  66. }
  67. try
  68. {
  69. action(_proxy);
  70. if (_isInError)
  71. {
  72. _isInError = false;
  73. LOG.Info(_serviceName + " 服务恢复");
  74. }
  75. return true;
  76. }
  77. catch (EndpointNotFoundException ex)
  78. {
  79. if (!_isInError)
  80. {
  81. _isInError = true;
  82. LOG.Error(_serviceName + " 连接已经断开。", ex);
  83. }
  84. }
  85. catch (ProtocolException ex)
  86. {
  87. if (!_isInError)
  88. {
  89. _isInError = true;
  90. LOG.Error(_serviceName + " 服务程序异常。", ex);
  91. }
  92. }
  93. catch (Exception ex)
  94. {
  95. if (!_isInError)
  96. {
  97. _isInError = true;
  98. LOG.Error(_serviceName + " 服务异常", ex);
  99. }
  100. }
  101. ((IClientChannel)_proxy).Abort();
  102. _proxy = _factory.CreateChannel();
  103. return false;
  104. }
  105. }
  106. }