langiriss 发表于 2013-1-26 15:16:25

一个简单的WCF通用请求类

public static class ServiceRequester<T>{      private static IDictionary<string, ChannelFactory<T>> _channelPool= new Dictionary<string, ChannelFactory<T>>();      private static object ayncLock = new object();      static private ChannelFactory<T> GetChannelFactory(string endPointName)      {            lock (ayncLock)            {                string cacheName = endPointName;                if (string.IsNullOrEmpty(endPointName))                {                  cacheName = typeof(T).Name;                }                ChannelFactory<T> _factory = null;                _channelPool.TryGetValue(cacheName, out _factory);                if (_factory == null)                {                  _factory = new ChannelFactory<T>(endPointName);                  _channelPool.Add(endPointName, _factory);                }                return _factory;            }      }      static public void Request(string endPointName, Action<T> action)      {            IClientChannel proxy = null;            try            {                lock (ayncLock)                {                  proxy = GetChannelFactory(endPointName).CreateChannel() as IClientChannel;                  proxy.Open();                  action((T)proxy);                  proxy.Close();                }             }            catch (CommunicationException communicationException)            {                if (proxy != null)                {                  proxy.Abort();                }                throw communicationException;            }            catch (TimeoutException timeoutException)            {                if (proxy != null)                {                  proxy.Abort();                }                throw timeoutException;            }            catch (Exception ex)            {                if (proxy != null)                {                  proxy.Abort();                }                throw ex;            }      }}

Usage:
ServiceRequester<ICalculateService>.Request("*", delegate(ICalculateService proxy)         {               proxy.Add(1, 4,1);         });
页: [1]
查看完整版本: 一个简单的WCF通用请求类