Dynamically calling a web service without a web reference in C#

Adding a web reference to your C# project and keeping it up to date, especially in times where many changes are being made, can be very tiresome. It occurred to me the other day that it must be possible to call a service on the fly in C# code using refection. Surely this functionality is included in the .Net framework. I was correct, it is, but it is not too well documented (Probably because it is slower at executing when compared with using a web reference – reflection etc…). However sometimes flexibility is more important than speed so I decided to look into implementing a solution.

Initially I had tired to read in the service’s WSDL via the ServiceDescription and parse it, however this proved to be very problematic and slow. Then in my travels around the many useless Google results I came across and Article on CodeProject.com by Ehsan Golkar. In this article Ehsan uses the ServiceDescription but loads the output into a ServiceDescriptionImporter. This then allows the creation of a compiled assembly into memory that will interface with the web service. Ehsan code seemed rather hard wired to his UI so I have taken the liberty to create a class that makes its operation much more generic.

Here is my Visual Studio solution which includes a test web service and a win forms application with uses ServiceInspector to call the test web service.

VS 2012 Solution Files for ServiceInspector

4 thoughts on “Dynamically calling a web service without a web reference in C#”

  1. Hi,
    Could you please let me know how to manage client side Session i.e “CookiesContainer” using above approach.

  2. Hi Shiva,

    I have updated the post with a new overloaded version of the RunMethod method. In here you can pass in a CookieContainer. The property is then accessed via reflection on the instantiated _service object. You will also be able to get to other properties in this way should you wish to.

    Hope that helps.

    Cheers,

    Andy

Leave a Reply

Your email address will not be published. Required fields are marked *