Introduction to WCF - Part 1 - A Simple Service

01 May 2011

A Brief History of Distributed Computing

At its heart, distributed computing has the key goal of opening-up applications and their data for reuse in other applications. Many solutions to developing distributed systems have evolved over the last two decades, all of which have pros and cons:

Pros Cons
Distributed Objects
COM and .NET Remoting successful in an all-Windows environment
Tightly-coupled (easily broken)
Difficult to create and support
Proprietary technologies
Message Brokers
(MSMQ, MQ Series)
Reliable & Robust Data-oriented
No open standard message format
Proprietary technologies
Web Services Loosely-coupled (resilient) Open standard message format (SOAP/XML) Open technologies (HTTP, XML) Performance issues
No inherent support for authentication, signing, etc.
No concept of state
Complex to extend (WS*)

Windows Communication Foundation

Introduced in .NET 3.0, the Windows Communication Foundation (WCF) provides a complete framework for the creation of distributed computing solutions with the following key elements:

  • A unified and consistent programming model
    • Brings together previous approaches like web services, remoting, message brokers, etc. into a single framework

  • Service-oriented architecture and loose-coupling
    • Between services (based on contracts)
    • From underlying bindings (HTTP, TCP, MSMQ, named pipes)

  • Support for WS* standards, a fully integrated security model and important constructs such as session state, publish-and-subscribe, transactions, etc.

With .NET 4, WCF is the preferred way of developing distributed computing solutions and (essentially) replaces .NET Remoting, Web Services, etc. Note that, if required, you can still develop and consume 'old-style' Web Services and create remoting-based solutions.

Simple WCF Service and Client

The following worked example demonstrates basic WCF principles and serves as a practical starting point for further explorations.

The Service

  • Start Visual Studio 2010 and select File | New | Project
  • From the New Project dialog, select WCF Service Application from the Visual C# > WCF template list:
  • Name the service WcfSimpleTextService and click OK
  • Using Solution Explorer, delete the files IService1.cs and Service1.svc (we'll create our own service files from scratch)
  • Right-click WcfSimpleTextService in Solution Explorer and select Add | New Item
  • Select WCF Service from Web templates and name the service TextService
  • Visual Studio will create three new files:
    1. ITextService.cs
      This is the contract for the service and takes the form of a .NET interface definition.

      Note the [ServiceContract] and [OperationContract] attributes which respectively mark the ITextService interface as being available as a WCF service, and the DoWork() method as being exposed to consumers of the service:
    2. TextService.svc
      The service definition mark-up file.

      By the default this simply references the CodeBehind file and specifies the service class:
    3. TextService.cs
      This is the C# definition of the service. Notice that this looks just like any normal C# class (there are no special WCF attributes or constructs):
  • Open TextService.cs and remove the DoWork() method
  • Now open ITextService.cs and remove the definition of DoWork()
  • In ITextService.cs, define two methods and decorate them with the [OperationContract] attribute
  • namespace WcfSimpleTextService
        public interface ITextService
            string SayHello();
            string Backwards(string text);
  • Now switch to the TextService.cs implementation file, right-click ITextService and select Implement Interface:
  • You should now see that Visual Studio has created stubs for the methods we need to define.
    Complete the definition of the methods as follows:
  • public string SayHello()
        return "Hello WCF";
    public string Backwards(string text)
        StringBuilder sb = new StringBuilder();
        for (int i = text.Length - 1; i > -1; i--)
        return sb.ToString();            
  • We've now completed our service. To quickly test it we can make use of Visual Studio's built-in ASP.NET Development Server.
    Right-click TextService.svc in Solution Explorer and select Set as Start Page
  • Now hit Ctrl+F5 to 'run' the service. You should see the development server start-up, along with the WCF Test Client application:
  • The WCF Test Client is very useful for basic testing as it allows you to invoke service methods and see the returned results
  • Double-click SayHello() in the Test Client and click Invoke. You should see "Hello WCF" returned as the response:
  • Now do the same for Backwards(). This time provide the required string parameter before clicking Invoke:

Deploying the Service

Now we know our service is working, we can deploy it to one of the following service hosts:

  • IIS 5/6, 7/7.5
    • Only supports the HTTP binding
    • Create a virtual directory
    • The .svc file works in a similar fashion to a .asmx web service file

  • Self-Hosting
    • The service is hosted by any Windows application (console, WPF, etc.)
    • You need to manage the start-up of the service
    • Supports all bindings

  • WAS
    • Windows Activation Service is a general-purpose host provided in Windows Vista/7 and Windows Server 2008
    • Hosting similar to the requirements of IIS 5/6
    • WAS takes care of intercepting calls to the WCF service and starts the necessary worker threads to support it
    • Support advanced features like app pooling, recycling, identity managements, etc.

  • Windows Server AppFabric
    • An extension to WAS designed to provide specific support for WCF and Workflow
    • Requires IIS 7.5 (part of Windows 7, Windows Server 2008 R2) and .NET 4
    • Provides additional features on top of WAS via the IIS console (monitoring, event tracking, state management, etc.)
    • Can be configured to auto-start WCF services (i.e. before a client calls it)

Deploying to IIS/AppFabric

Here we’ll review the basic process of using AppFabric to host SimpleTextService. First, download and install AppFabric from here:

  1. Start IIS 7.5 management console by hitting [Windows Key] (or click the Start button) and type IIS
  2. Hit Return to run Internet Information Service (IIS) Manager
  3. Right-click Default Web Site and select Add Application
    (an IIS 7 Application is similar to an IIS 5/6 Virtual Directory, in addition it has an associated application pool):
  4. Enter SimpleTextService as an alias for the service, leave the default app pool and provide the full path to the folder containing TextService.svc. Then click OK:
  5. Now right-click the newly created SimpleTextService service and select Edit Permissions
  6. Make sure that either the IIS_IUSRS or Everybody account has Read & execute, List folder contents and Read permissions on the folder containing the service:
  7. Switch to Content View, right-click TextService.svc and select Browse
  8. You should now see your default browser start and display the following page:
  9. Copy the URL of the service, we’ll need in the next step when we create a simple client application

Creating a Simple Service Client

  1. Start a new instance of Visual Studio 2010 and create a new WPF project (this can be anything you like, I’ve chosen a WPF application for simplicity)
  2. Create a simple interface as follows:
  3. Now we need to add a reference to the service. This is similar to the process used to add old-style web service references.
    Right-click References in Solution Explorer and select Add Service Reference:
  4. Paste the URL of the service we added to IIS and click Go (notice that you don’t have specify the ...?wsdl query string value):
  5. Type a name for the reference (e.g. TextService) then click OK
  6. Visual Studio now creates the proxy object we’ll use to communicate with our service (note that the proxy for the actual service object will be named TextServiceClient)
  7. Now create event handlers for the two buttons and add the following code:
  8. public partial class MainWindow : Window
        private TextService.TextServiceClient m_textService;
        public MainWindow()
            m_textService = new TextService.TextServiceClient();
        private void buttonSayHello_Click(object sender, RoutedEventArgs e)
            textBoxResult.Text = m_textService.SayHello();
        private void buttonReverse_Click(object sender, RoutedEventArgs e)
            textBoxResult.Text = m_textService.Backwards(textBoxInput.Text);
  9. Run the application and test it:

This concludes part one of our introduction to WCF. In part two we'll take a look at self-hosting WCF services.