wcf Your first service First Service Client


Example

Let's say you have a service the same as the one defined in the "First service and host" example.

To create a client, define the client configuration section in the system.serviceModel section of your client configuration file.

<system.serviceModel>
  <services>
    <client name="Service.Example">
      <endpoint name="netTcpExample" contract="Service.IExample" binding="netTcpBinding" address="net.tcp://localhost:9000/Example" />
    </client>
  </services>      
</system.serviceModel>

Then copy the service contract definition from the service:

namespace Service
{
    [ServiceContract]
    interface IExample
    {
        [OperationContract]
        string Echo(string s);
    }
}

(NOTE: You could also consume this via adding a binary reference instead to the assembly containing the service contract instead.)

Then you can create the actual client using ChannelFactory<T>, and call the operation on the service:

namespace Console
{
    using Service;
  
    class Console
    {
        public static void Main(string[] args)
        {
            var client = new System.ServiceModel.ChannelFactory<IExample>("Service.Example").CreateChannel();
            var s = client.Echo("Hello World");
            Console.Write(s);
            Console.Read();
        }
    }
}