1.将服务接口类如IService.cs拷贝至客户端项目中
2.创建工厂类WcfChannelFactory封装问方法
/// <summary>
/// 使用ChannelFactory为wcf客户端创建独立通道
/// </summary>
public class WcfChannelFactory
{
public WcfChannelFactory()
{
}
/// <summary>
/// 执行方法 nettcpbinding 绑定方式
/// </summary>
/// <typeparam name="T">服务接口</typeparam>
/// <param name="pUrl">wcf地址</param>
/// <param name="pMethodName">方法名</param>
/// <param name="pParams">参数列表</param>
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;
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;
}
}
}
}
}
3.调用,客户端使用类似如下代码调用服务接口:
WcfChannelFactory.ExecuteMethod<IService>("net.tcp://192.168.0.1:1128/mex", "Test", pParams1,pParams2,pParams3)
需要使用返回值,则对object类型的返回值进行强制转换,如:
string sResult=(string)WcfChannelFactory.ExecuteMethod<IService>("net.tcp://192.168.0.1:1128/mex", "Test", pParams1,pParams2,pParams3)