動態調用WCF服務


本文轉載:http://www.cnblogs.com/wiseant/archive/2010/07/29/1787599.html

原文地址:http://blog.csdn.net/castlooo/archive/2010/05/06/5562619.aspx

 

客戶端調用wcf ,有時需要動態的調用服務端的WCF中的方法,本方法,反射wcf 的接口,動態調用接口中的方法。

主要為,動態綁定,反射動態調用。

 

復制代碼
public static object ExecuteMethod<T>(string pUrl,string pMethodName, params object[] pParams)  
{  
    EndpointAddress address = new EndpointAddress(pUrl);  
    Binding bindinginstance = null;  
    NetTcpBinding ws = new NetTcpBinding();  
    ws.MaxReceivedMessageSize = 20971520;  
    ws.Security.Mode = SecurityMode.None;  
    bindinginstance = ws;  
    using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance,address))  
    {  
        T instance = channel.CreateChannel();  
        using (instance as IDisposable)  
        {  
            try  
            {  
                Type type = typeof(T);  
                MethodInfo mi = type.GetMethod(pMethodName);  
                return mi.Invoke(instance, pParams);  
            }  
            catch (TimeoutException)  
            {  
                (instance as ICommunicationObject).Abort();  
                throw;  
            }  
            catch (CommunicationException)  
            {  
                (instance as ICommunicationObject).Abort();  
                throw;  
            }  
            catch (Exception vErr)  
            {  
                (instance as ICommunicationObject).Abort();  
                throw;  
            }  
        }  
    }  
}  
復制代碼

 

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

調用方法使用

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

 

 

另外還有一篇貼子可參考:http://hi.baidu.com/meback/blog/item/c140495447258e5d564e0006.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM