Kirk Evans Blog

.NET From a Markup Perspective

Dynamically Invoking Web Services… With WCF This Time

Awhile back, I posted on Dynamically Invoking Web Services using ASMX.  To do this, we used a little nasty bit of CodeDOM trickery and reflection, something that just isn’t needed with WCF.  Take a look at how much easier this is using WCF.

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());

EndpointAddress address = 
    new EndpointAddress("http://localhost:43288/WCFService1/Service.svc");
IRequestChannel irc = factory.CreateChannel(address);
using (irc as IDisposable)
    XmlReader reader = XmlReader.Create(new StringReader(
@"<GetDataUsingDataContract xmlns=''>
<composite xmlns:a='' 
    Message m = Message.CreateMessage(MessageVersion.Soap11,
        "", reader);
    Message ret = irc.Request(m);

//close the factory

To test this, I simply used Visual Studio 2008 to create a new WCF Service.  I changed the binding from wsHttpBinding to basicHttpBinding, and the rest stays the same.

One of the neat things about the original post was that you could download the definition and compile it.  You could still do the same operations here and use that to serialize into an object used in the CreateMessage method.