在网上找了好久关于怎么动态调用WCF而不需要添加服务引用, 结果所有的结果都是需要知道服务器端的接口类型, 也下载过源代码看, 结果一看确实是客户端引用服务器端,得到接口类型, 我想请问到底有没有什么方法不需要知道这个接口的
代码如下:
static void Main(string[] args)
{
string url = "net.tcp//localhost:10166/Dawson.svc";
object dpser = ExecuteMethod<IService>(url,"ShowName","dawson");
string a= (dpser as IService).ShowName("dawson");
Console.WriteLine(a);
}
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;
}
}
}
}
如果不添加引用,怎么能知道IService这个接口!! 如果需要引用,我觉得Web服务就失去它应有的意义了
IService你定义到一个公共库,只要引用公共库了
如果这个接口是别人提供的,人家怎么会让你引用呢?
@何其菜: 这个情况不多吧,实在要这样用,参考这个: http://www.codeproject.com/Articles/499986/WebControls/ 估计效率有点影响