Code Library.... C# | Microsoft.Net

Dynamic Webservice Invoke

Recently in one of the project which i am working i came into such a situation in which i need to read a number of web service URL’s, then dynamically call a particular method in it. First i thought of going with reflection alone but further analysis led me to more in depths of reflection which includes a bit of dynamic compilation thereby to create a “webproxy” like stuff at runtime. Thus we can get the actual metadata of the target type using which we can invoke the required method. Here we might need the type definition of the method and return parameter too (if any).

Luckily i just had a common return type which i don’t have to worry too much about. Now that we decided to go with dynamic compilation in .Net Clr and reflection we need to start with a ServiceDescriptionclass to which we can assign a stream which will in turn read the required data from a WSDL URL, a ServiceDescriptionImporter class to import it. Now we need to add the necessary references and do the compilation as required.

Below is just the main part of the code for dynamic compilation in C#


ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter imp = new ServiceDescriptionImporter();
imp.ProtocolName = "Soap"; // Use SOAP
imp.AddServiceDescription(description, null, null);

CodeNamespace namspace = new CodeNamespace();
CodeCompileUnit unt = new CodeCompileUnit();
ServiceDescriptionImportWarnings warning = imp.Import(namspace, unt);
if (warning == 0)
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider.CompileAssemblyFromDom(parms, unt);
object o = results.CompiledAssembly.CreateInstance("MyService");
Type t = o.GetType();

And now we can dynamically invoke webservice method with the following code

t.InvokeMember("MyParam", System.Reflection.BindingFlags.InvokeMethod, null, o, null);


For the full source code visit C# source code on Dynamically generating webproxy

For updated Source code and article, visit A-Generic-and-Dynamic-way-to-invoke-remote-WCFWebservice-Web-Method

blog comments powered by Disqus