本文转载:
原文地址:
客户端调用wcf ,有时需要动态的调用服务端的WCF中的方法,本方法,反射wcf 的接口,动态调用接口中的方法。
主要为,动态绑定,反射动态调用。
1 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public static object ExecuteMethod(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 channel = new ChannelFactory (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[] { "参数" })
另外还有一篇贴子可参考: