C# 如何动态调用wcf,没有代理类的情况下
因为是地址、方法名都不确定,无法确定接口类型。
//动态调用wcf服务
public static object CreateWCFServiceByURL<T>(string url, string bing, string pMethodName, params object[] pParams)
{
if (string.IsNullOrEmpty(url)) throw new NotSupportedException("this url isn`t Null or Empty!");
EndpointAddress address = new EndpointAddress(url);
Binding binding = CreateBinding(bing);
ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
T instance = factory.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 ex)
{
(instance as ICommunicationObject).Abort();
throw;
}
finally
{
GC.Collect();
}
}
}