动态调用WCF服务

1.方法定义

/// <summary>
        /// 动态调用服务
        /// </summary>
        /// <typeparam name="T">调用服务的契约接口</typeparam>
        /// <param name="pUrl">服务发布地址</param>
        /// <param name="pMethodName">方法名称</param>
        /// <param name="pParams">方法参数</param>
        /// <param name="binding">数据传输绑定协议</param>
        /// <returns>返回值</returns>
        public static object ExecuteMethod<T>(string pUrl, string pMethodName, object[] pParams,string binding)
        {
            if (_dicChannel == null)
                _dicChannel = new Dictionary<string, object>();
            DateTime StartTime = DateTime.Now;
            EndpointAddress address = new EndpointAddress(pUrl);
            Binding bding = ServiceExecuteMethod.GetServiceBinding(binding);

            T instance;
            if (_dicChannel.ContainsKey(pUrl))
                instance = (T)_dicChannel[pUrl];
            else
            {
                ChannelFactory<T> channel = new ChannelFactory<T>(bding, address);
                channel.Endpoint.Behaviors.Add(new ContextTransmitBehaviorAttribute());
                instance = channel.CreateChannel();
                _dicChannel.Add(pUrl, instance);
            }

            try
            {
                Type type = typeof(T);
                MethodInfo mi = type.GetMethod(pMethodName);
                object ret = mi.Invoke(instance, pParams);
                DateTime EndTime = DateTime.Now;
                                
                if (InsertServiceElapsedLog != null)
                {
                    //InsertServiceElapsedLog(pUrl, pMethodName, StartTime, EndTime, (EndTime - StartTime).TotalMilliseconds.ToString());
                }

                return ret;
            }
            catch (Exception ex)
            {
                //(instance as ICommunicationObject).Abort();
                throw ex.InnerException;
            }
        }
View Code

2.调用方法

byte[] dsArray = ServiceExecuteMethod.ExecuteMethod<IBaseData>(Config.ReadValueByKey(CommonString.IBaseDataUrl), "GetHospitalIndividualImg", new object[] { Id }, Config.ReadValueByKey(CommonString.IBaseDataUrlBinding)) as byte[];
View Code
原文地址:https://www.cnblogs.com/seacher/p/8565982.html