Tuesday, November 27, 2012

WCF : A simple WCF client example

This post shows a simple WCF client example which consumes a WCF service in previouse post. Most common way of using a WCF service is using proxy in client application. And the proxy is created either by using Visual Studio Add Service Reference or by using svcutil.exe tool.

(1) Run Visual Studio
(2) New Project - [Console Application]
(3) Rightclick on Project node in Solution Explorer and choose [Add Service Reference]
(4) Specify WCF service address in [Address] combobox and click [Go]. Services and Operations will be shown as below. Change Namespace at the bottom. This is the namespace for proxy.
(5) In project, a Service Reference and app.config will be added.

(6) To use a WCF service, we can use Proxy Client which is automatically generated from Add Service Reference and this is most common scenario. However, if we do not want to rely on proxy client, we can use ChannelFactory with having service interface only. Here we write a WCF client code in Program.cs.
using System;
using System.ServiceModel;
using SimpleWcfClient.MySimpleService;

namespace SimpleWcfClient
    class Program
        static void Main(string[] args)
            // 1. Using Proxy client
            SimpleServiceClient client = new SimpleServiceClient();
            string result = client.SayHello("Tom");

            // 2. Using ChannelFactory
            WSHttpBinding binding = new WSHttpBinding();
            EndpointAddress address = new EndpointAddress("http://localhost:8088/SimpleService.svc");
            ChannelFactory<ISimpleService> factory = new ChannelFactory<ISimpleService>(binding, address);
            ISimpleService iSimple = factory.CreateChannel();
            using (iSimple as IDisposable)
                result = iSimple.SayHello("Jerry");

(7) App.config has endpoint information (not must have but proxy client above uses this config since no endpoint was passed in constructor). This assumes WCF service is hosted in IIS.
<?xml version="1.0" encoding="utf-8" ?>
                <binding name="WSHttpBinding_ISimpleService" />
            <endpoint address="http://localhost:8088/SimpleService.svc" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_ISimpleService" contract="MySimpleService.ISimpleService"

No comments:

Post a Comment