动态调用WCF服务

作者:互联网   出处:控件中国网   2014-11-05 19:21:03   阅读:1

动态调用WCF服务

客户端调用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[] { "参数" })

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat