Kirk Evans Blog

.NET From a Markup Perspective

Call Web Service Proxies via Reflection

I received an odd question from a mailing list that I am on.  The poster wanted to iterate through the Web References for the current project and call a method that appears on each endpoint.  The first thing that popped into my mind was, “Why does every single endpoint that you reference have the same method?!?”  That means there is an early bound reference to multiple endpoints, where each endpoint shares the same method… I absolutely cannot think of a use case where this seems justifiable. 

The code to do this is pretty simple, I just use reflection to locate the types in the current assembly, determine if the type derives from SoapHttpClientProtocol, and calls the method.  More an interesting demo of reflection than a usable piece of code.  Interesting, just not applicable.

 

System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
foreach(System.Type type in a.GetTypes())
{
 if(type.IsSubclassOf(typeof(System.Web.Services.Protocols.SoapHttpClientProtocol)))
 {     
  object proxy = a.CreateInstance(type.FullName,false);
  MethodInfo mi = proxy.GetType().GetMethod(“HelloWorld”);
  string ret = Convert.ToString(mi.Invoke(proxy,new object[0]));
  System.Console.WriteLine(ret);
 }
}