代码改变世界

WCF通用服务请求类

2010-09-12 22:58  ruinet  阅读(555)  评论(0编辑  收藏  举报

 

类代码:

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

使用:

 ServiceRequester<ICalculateService>.Request("*", delegate(ICalculateService proxy)
            {
                proxy.Add(1, 4,1);
            });

free web counter