Creating a WCF Service

This tutorial guides you through the fundamental steps of creating a basic Windows Communication Foundation (WCF) service. WCF is a unified programming model for building secure, reliable, transactional, and interoperable distributed applications.

Prerequisites

  • Visual Studio 2008 or later installed.
  • Understanding of C# or Visual Basic .NET.

Step 1: Define a Service Contract

A service contract defines the operations a service exposes to its clients. It's an interface decorated with the [ServiceContract] attribute.

Example: ICalculatorService.cs


using System.ServiceModel;

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    double Add(double operand1, double operand2);

    [OperationContract]
    double Subtract(double operand1, double operand2);

    [OperationContract]
    double Multiply(double operand1, double operand2);

    [OperationContract]
    double Divide(double operand1, double operand2);
}
                

Step 2: Implement the Service

Create a class that implements the service contract interface. This class contains the actual logic for each operation.

Example: CalculatorService.cs


using System.ServiceModel;

public class CalculatorService : ICalculatorService
{
    public double Add(double operand1, double operand2)
    {
        return operand1 + operand2;
    }

    public double Subtract(double operand1, double operand2)
    {
        return operand1 - operand2;
    }

    public double Multiply(double operand1, double operand2)
    {
        return operand1 * operand2;
    }

    public double Divide(double operand1, double operand2)
    {
        if (operand2 == 0)
        {
            throw new FaultException("Division by zero is not allowed.");
        }
        return operand1 / operand2;
    }
}
                

Step 3: Configure the Service (App.config)

The application configuration file (App.config for a console or desktop application, or Web.config for a web application) is used to configure the service's endpoints and behaviors.

Example: App.config


<configuration>
    <system.serviceModel>
        <services>
            <service name="CalculatorService" behaviorConfiguration="CalculatorServiceBehavior">
                <!-- Service Endpoints -->
                <endpoint address="" binding="basicHttpBinding" contract="ICalculatorService" />
                <!-- Metadata endpoint -->
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="CalculatorServiceBehavior">
                    <!-- serviceMetadata enables the generation of metadata, which is used to generate help pages and proxy classes -->
                    <serviceMetadata httpGetEnabled="True"/>
                    <!-- serviceDebug enables error details to be sent to the client -->
                    <serviceDebug includeExceptionDetailInFaults="False"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>
                
Important: The address attribute in the endpoint tag can be used to specify a relative or absolute address. If left empty, it uses the base address configured for the service host. The mex endpoint is crucial for WCF's metadata exchange mechanism.

Step 4: Host the Service

To make the service accessible, it needs to be hosted. This can be done using different hosting environments:

  • Self-Hosting: Using ServiceHost in a console application or Windows Service.
  • IIS Hosting: Deploying the service to Internet Information Services (IIS).
  • Windows Server AppFabric Hosting: For managed hosting scenarios.

Example: Self-Hosting in a Console Application


using System;
using System.ServiceModel;

class Program
{
    static void Main(string[] args)
    {
        // Create a ServiceHost for the CalculatorService.
        using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
        {
            // Open the ServiceHost to create listeners and start listening for messages.
            serviceHost.Open();

            // The service can be accessed at http://localhost:8731/Design_Time_Addresses/CalculatorService/
            Console.WriteLine("The Calculator service is ready.");
            Console.WriteLine("Press  to exit.");
            Console.ReadLine();

            // Close the ServiceHost.
            serviceHost.Close();
        }
    }
}
                

Step 5: Create a Client

Clients can connect to the WCF service by generating a proxy class from the service's metadata. This can be done using the svcutil.exe tool or through Visual Studio's "Add Service Reference" feature.

Example: Client Code


using System;
using ServiceReference1.CalculatorService; // Assuming this namespace after adding service reference

class Program
{
    static void Main(string[] args)
    {
        // Create a channel to the service.
        CalculatorServiceClient client = new CalculatorServiceClient();

        try
        {
            // Call the service operations.
            double result = client.Add(5.0, 3.0);
            Console.WriteLine($"Addition: 5.0 + 3.0 = {result}");

            result = client.Subtract(10.0, 4.0);
            Console.WriteLine($"Subtraction: 10.0 - 4.0 = {result}");

            result = client.Multiply(6.0, 7.0);
            Console.WriteLine($"Multiplication: 6.0 * 7.0 = {result}");

            result = client.Divide(15.0, 3.0);
            Console.WriteLine($"Division: 15.0 / 3.0 = {result}");

            // Example of handling a fault
            try
            {
                client.Divide(10.0, 0.0);
            }
            catch (FaultException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        finally
        {
            // Close the client channel.
            client.Close();
        }

        Console.WriteLine("Press  to exit.");
        Console.ReadLine();
    }
}
                

Conclusion

You have successfully created, configured, and hosted a basic WCF service, and built a client application to consume it. This tutorial covers the essentials, and WCF offers a wide range of features for building more complex distributed applications, including security, transactions, and various communication protocols.