Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 3.0
 How to: Run a Basic Service

  Switch on low bandwidth view
This page is specific to
.NET Framework 3.0

Other versions are also available for the following:
How to: Run a Basic Windows Communication Foundation Service

This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:

  • Create a base address for the service.

  • Create a service host for the service.

  • Enable metadata exchange.

  • Open the service host.

Once the service is running, the next step is to create a client to access the service. For the procedure that describes this step, see How to: Create a Windows Communication Foundation Client.

This topic is one of a series that shows you how to create a service and client application. For an overview, see Getting Started Tutorial.

To configure a base address for the service

  • Create a Uri instance for the base address of the service.

    Visual Basic
    Dim baseAddress As New Uri("http://localhost:8000/ServiceModelSamples/Services")
    
    C#
    Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");
    

Host the service

  1. Create a new ServiceHost instance to host the service. You must specify the type that implements the service contract and the base address. For this sample we specify the base address as http://localhost:8000/ServiceModelSamples/GettingStarted and CalculatorService as the type that implements the service contract.

    Visual Basic
    Dim serviceHost As New ServiceHost(GetType(CalculatorService), baseAddress)
    
    C#
    ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);
    
  2. Add an endpoint that exposes the service. To do this, you must specify the contract that the endpoint is exposing, a binding, and the address for the endpoint. For this sample we specify ICalculator as the contract, WSHttpBinding as the binding, and CalculatorService as the address. Notice here that we are specifying a relative address. The full address for the endpoint is the combination of the base address and the endpoint address. In this case the full address is http://localhost:8000/ServiceModelSamples/GettingStarted/CalculatorService.

    Visual Basic
    ' Add a service endpoint
    serviceHost.AddServiceEndpoint( _
        GetType(ICalculator), _
        New WSHttpBinding(), _
        "CalculatorService")
    
    C#
    // Add a service endpoint
    serviceHost.AddServiceEndpoint(
        typeof(ICalculator),
        new WSHttpBinding(),
        "CalculatorService");
    
  3. Enable Metadata Exchange. To do this we must add a service metadata behavior. First we create a ServiceMetadataBehavior instance, set the HttpGetEnabled property to true, and then add the new behavior to the service. For more information about security issues when publishing metadata, see Security Considerations with Metadata.

    Visual Basic
    ' Enable metadata exchange
    Dim smb As New ServiceMetadataBehavior()
    smb.HttpGetEnabled = True
    serviceHost.Description.Behaviors.Add(smb)
    
    C#
    // Enable metadata exchange
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    serviceHost.Description.Behaviors.Add(smb);
    
  4. Open the ServiceHost and wait for incoming messages. When the user presses the ENTER key, close the ServiceHost.

    Visual Basic
    serviceHost.Open()
    Console.WriteLine("The service is ready.")
    Console.WriteLine("Press <ENTER> to terminate service.")
    Console.WriteLine()
    Console.ReadLine()
    
    ' Close the ServiceHostBase to shutdown the service.
    serviceHost.Close()
    
    C#
    serviceHost.Open();
    Console.WriteLine("The service is ready.");
    Console.WriteLine("Press <ENTER> to terminate service.");
    Console.WriteLine();
    Console.ReadLine();
    
    // Close the ServiceHostBase to shutdown the service.
    serviceHost.Close();
    

Example

The following example includes the service contract and implementation from previous steps in the tutorial and hosts the service in a console application. Compile the following into an executable named Service.exe.

Be sure to reference System.ServiceModel when compiling the code.

Visual Basic
Imports System
Imports System.ServiceModel
Imports System.ServiceModel.Description

Module Service
    ' Define a service contract.
    <ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
    Public Interface ICalculator
        <OperationContract()> _
        Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
    End Interface

    ' Service class that implements the service contract.
    ' Added code to write output to the console window.
    Public Class CalculatorService
        Implements ICalculator
        Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
            Dim result As Double = n1 + n2
            Console.WriteLine("Received Add({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        End Function

        Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
            Dim result As Double = n1 - n2
            Console.WriteLine("Received Subtract({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        End Function

        Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
            Dim result As Double = n1 * n2
            Console.WriteLine("Received Multiply({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        End Function

        Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
            Dim result As Double = n1 / n2
            Console.WriteLine("Received Divide({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        End Function
    End Class

    Class Program
        Shared Sub Main()
            Dim baseAddress As New Uri("http://localhost:8000/ServiceModelSamples/Services")
            Dim serviceHost As New ServiceHost(GetType(CalculatorService), baseAddress)
            Try
                ' Add a service endpoint
                serviceHost.AddServiceEndpoint( _
                    GetType(ICalculator), _
                    New WSHttpBinding(), _
                    "CalculatorService")
                ' Enable metadata exchange
                Dim smb As New ServiceMetadataBehavior()
                smb.HttpGetEnabled = True
                serviceHost.Description.Behaviors.Add(smb)
                serviceHost.Open()
                Console.WriteLine("The service is ready.")
                Console.WriteLine("Press <ENTER> to terminate service.")
                Console.WriteLine()
                Console.ReadLine()

                ' Close the ServiceHostBase to shutdown the service.
                serviceHost.Close()
            Catch ce As CommunicationException
                Console.WriteLine("An exception occured: {0}", ce.Message)
                serviceHost.Abort()
            End Try
        End Sub
    End Class

C#
using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }

    // Service class that implements the service contract.
    // Added code to write output to the console window.
    public class CalculatorService : ICalculator
    {
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            Console.WriteLine("Received Add({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            Console.WriteLine("Received Subtract({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            Console.WriteLine("Received Multiply({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            Console.WriteLine("Received Divide({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");
            ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);
            try
            {
                // Add a service endpoint
                serviceHost.AddServiceEndpoint(
                    typeof(ICalculator),
                    new WSHttpBinding(),
                    "CalculatorService");
                // Enable metadata exchange
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                serviceHost.Description.Behaviors.Add(smb);
                serviceHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                serviceHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occured: {0}", ce.Message);
                serviceHost.Abort();
            }
        }
    }
}

To run the service, launch Service.exe.

Verify that the service is running by navigating to the service's debug page at http://localhost:8000/ServiceModelSamples/Service.

NoteNote:

Services such as this one require permission to register HTTP addresses on the machine for listening. Administrator accounts have this permission, but non-administrator accounts must be granted permission for HTTP namespaces. For more information about how to configure namespace reservations, see Configuring HTTP and HTTPS.

In addition to hosting a WCF service in a managed application, this sample configures the service in code. Services can also be configured within a configuration file. For more information about using a configuration file see Configuring Services Using Configuration Files. Services can also be hosted under Internet Information Services (IIS). For more information about how to do this, see How to: Host a WCF Service in IIS.

See Also

Footer image

Send comments about this topic to Microsoft.
© Microsoft Corporation. All rights reserved.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker