WCF Tutorial, Part 6: Create a Custom Service Host

01. December 2013 WCF 0

You can host WCF services on any hosts, include: Windows Form, WPF, Windows Services, Windows Activation Services (WAS), IIS, or a Console Application.

  • Add a new Console Application to the solution and name it RoomReservationServiceHost
  • Add reference to:
    • RoomReservationService
    • RoomReservationContract
    • System.ServiceModel
  • Copy the necessary configurations from the Service’s App.config into the project’s App.config.

    Note that we have added the Service Behavior and Base Address programmatically.

  • Modify the Program.cs as below:


using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using RoomReservationService;
namespace RoomReservationServiceHost
    class Program
        internal static ServiceHost serviceHost = null;
        internal static void StartService()
                serviceHost = new ServiceHost(typeof(RoomReservationService.RoomReservationService), 
                    new Uri("http://localhost:9000/RoomReservation"));
                serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
            catch (AddressAccessDeniedException)
                Console.WriteLine("Either start Visual Studio in elevated admin " +
                    "mode or register the listener port with netsh.exe");
        internal static void StopService()
            if (serviceHost != null && serviceHost.State == CommunicationState.Opened)
        static void Main(string[] args)
            Console.WriteLine("Server is running. Press return to exit");

The ServiceBehavior which has added is to allow creating a client application by using WSDL.

The service is started by instantiating and opening an object of type ServiceHost in System.ServiceModel namespace.

ServiceHost implements the host used by the WCF service model programming model. ServiceHost class is used in order to configure and expose a service for use by client applications when you are not using IIS or WAS to expose a service. Both IIS and WAS interact with a ServiceHost object on your behalf.

To expose a service for use by callers, WCF requires a complete service description (represented by the ServiceDescription class). The ServiceHost class creates a ServiceDescription from the service type and configuration information and then uses that description to create ChannelDispatcher objects for each endpoint in the description.

Use a ServiceHost object to load a service, configure endpoints, apply security settings, and start listeners to handle incoming requests.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.