客户端动态调用WCF服务中的方法

客户端调用wcf ,有时需要动态的调用服务端的WCF中的方法,本方法,反射wcf 的接口,动态调用接口中的方法。

主要为,动态绑定,反射动态调用。


[c-sharp]  view plain copy
  1. public static object ExecuteMethod<T>(string pUrl,string pMethodName, params object[] pParams)  
  2.        {  
  3.            EndpointAddress address = new EndpointAddress(pUrl);  
  4.            Binding bindinginstance = null;  
  5.            NetTcpBinding ws = new NetTcpBinding();  
  6.            ws.MaxReceivedMessageSize = 20971520;  
  7.            ws.Security.Mode = SecurityMode.None;  
  8.            bindinginstance = ws;  
  9.            using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance,address))  
  10.            {  
  11.                T instance = channel.CreateChannel();  
  12.                using (instance as IDisposable)  
  13.                {  
  14.                    try  
  15.                    {  
  16.                        Type type = typeof(T);  
  17.                        MethodInfo mi = type.GetMethod(pMethodName);  
  18.                        return mi.Invoke(instance, pParams);  
  19.                    }  
  20.                    catch (TimeoutException)  
  21.                    {  
  22.                        (instance as ICommunicationObject).Abort();  
  23.                        throw;  
  24.                    }  
  25.                    catch (CommunicationException)  
  26.                    {  
  27.                        (instance as ICommunicationObject).Abort();  
  28.                        throw;  
  29.                    }  
  30.                    catch (Exception vErr)  
  31.                    {  
  32.                        (instance as ICommunicationObject).Abort();  
  33.                        throw;  
  34.                    }  
  35.                }  
  36.            }  
  37.        }  
 


本文使用的是nettcpbinding 绑定方式,可修改。

调用方法使用

ExecuteMethod<IService>("net.tcp://192.168.0.1:8001/mex", "Test", new object[] { "参数" })

转载于:https://my.oschina.net/dyg540/blog/84620

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值