WCF 101: The Simplest WCF Example You'll Ever See

Every once in a while, I’ll encounter a developer that thinks that WCF is too complicated to use. Whereas in fact, the basics of WCF are incredibly simple. MSDN’s tutorial hides this fact by making their introduction to WCF a fairly long and painful 6-step process, but you need much less to write your first WCF application. In fact, you don’t need Visual Studio and you don’t even need svcutil. All you need is notepad, and an install of .NET 3.0.

 

I have three steps for you:

 

1. Copy the following code into a file called “WCF.cs” using your text editor of choice:

 

using System;

using System.ServiceModel;

class Program

{

    static void Main()

    {

        ServiceHost host = new ServiceHost(typeof(Echo));

        host.AddServiceEndpoint(typeof(IEcho), new BasicHttpBinding(), "https://localhost/Service");

        host.Open();

        ChannelFactory<IEcho> client = new ChannelFactory<IEcho>(new BasicHttpBinding(), "https://localhost/Service");

        Console.WriteLine(client.CreateChannel().Echo("hello"));

    }

}

[ServiceContract]

interface IEcho

{

    [OperationContract]

    string Echo(string s);

}

class Echo : IEcho

{

    string IEcho.Echo(string s) { return s + " echoooOOooo"; }

}

2. Compile the code by running the C# compiler csc.exe against your new WCF.cs file. You can usually just run this in a command prompt:

 

C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe WCF.cs

 

3. Still in the command prompt, run WCF.exe. You should get the output:

 

hello echoooOOooo

 

                indicating that you started a service, created a client, and made a call to your service’s “Echo” method.

 

Voila! That’s all you need to use WCF. Not too bad, right?