Hosting a service in a console application

When creating a simple demo program for .NET framework, we will probably choose a console application. At the same, when talking about WCF service hosting, the console-hosting scenario is the most convenient one, which is especially handy and useful when we want to do some quick demo or testing on some WCF functionality.

How to do it...

  1. Create a .NET framework-based Console project through Visual Studio.

    Visual Studio provides various project templates for creating a .NET framework-based application. For our sample console-hosting service here, we will choose the Console Application project type from the Visual Studio New Project wizard.

    How to do it...
  2. Add a new WCF service into the project.

    We can simply accomplish this by using the Add New Item function in Visual Studio and choose WCF Service as the item type from Visual Studio's Add New Item UI.

    How to do it...
  3. Add code into the Main function to start up the WCF service. The following code shows the typical Main function that starts up a WCF service in a console application: static void Main(string[] args)
    {
       using (ServiceHost consoleHost = new ServiceHost(typeof(TestService)))
       {
          consoleHost.Open();
          Console.WriteLine("press any key to stop service host...");
          Console.ReadLine();
       }
    }

How it works...

When you add a new WCF Service item in Visual Studio, the IDE actually helps you to finish the following three tasks:

  • Creating a ServiceContract interface.
  • Creating a Service class that implements the ServiceContract interface.

    The following code shows the sample ServiceContract and implementation class used in this recipe.

    [ServiceContract]
     public interface ITestService
        {
            [OperationContract]
            void DoWork();
        }
    
     public class TestService : ITestService
        {
            public void DoWork()
            {
            }
        }
  • Adding the service endpoint and binding configuration in the App.config file.

In addition to the Contract and service type, the IDE will also insert a default configuration setting for the endpoint that can be exposed through the service. The following screenshot shows the sample service configuration section that contains a single endpoint, which uses WSHttpBinding.

How it works...

With the code and configuration entries as defined previously, we can start our service host by supplying the service type in the constructor of the ServiceHost class.

using (ServiceHost consoleHost = new ServiceHost(typeof(TestService)))

What the runtime will do is, it will lookup the configuration file and load the <service> entry that has the name identical to the type specified in the constructor, and launch the service and endpoints defined in it.

See also

  • Complete source code for this recipe can be found in the \Chapter 3\recipe1\ folder