Tutorial: Host and run a basic Windows Communication Foundation service - WCF (2024)

  • Article

This tutorial describes the third of five tasks required to create a basic Windows Communication Foundation (WCF) application. For an overview of the tutorials, see Tutorial: Get started with Windows Communication Foundation applications.

The next task for creating a WCF application is to host a WCF service in a console application. A WCF service exposes one or more endpoints, each of which exposes one or more service operations. A service endpoint specifies the following information:

  • An address where you can find the service.
  • A binding that contains the information that describes how a client must communicate with the service.
  • A contract that defines the functionality that the service provides to its clients.

In this tutorial, you learn how to:

  • Create and configure a console app project for hosting a WCF service.
  • Add code to host the WCF service.
  • Update the configuration file.
  • Start the WCF service and verify it's running.

Create and configure a console app project for hosting the service

  1. Create a console app project in Visual Studio:

    1. From the File menu, select Open > Project/Solution and browse to the GettingStarted solution you previously created (GettingStarted.sln). Select Open.

    2. From the View menu, select Solution Explorer.

    3. In the Solution Explorer window, select the GettingStarted solution (top node), and then select Add > New Project from the shortcut menu.

    4. In the Add New Project window, on the left side, select the Windows Desktop category under Visual C# or Visual Basic.

    5. Select the Console App (.NET Framework) template, and enter GettingStartedHost for the Name. Select OK.

  2. Add a reference in the GettingStartedHost project to the GettingStartedLib project:

    1. In the Solution Explorer window, select the References folder under the GettingStartedHost project, and then select Add Reference from the shortcut menu.

    2. In the Add Reference dialog, under Projects on the left side of the window, select Solution.

    3. Select GettingStartedLib in the center section of the window, and then select OK.

      This action makes the types defined in the GettingStartedLib project available to the GettingStartedHost project.

  3. Add a reference in the GettingStartedHost project to the System.ServiceModel assembly:

    1. In the Solution Explorer window, select the References folder under the GettingStartedHost project, and then select Add Reference from the shortcut menu.

    2. In the Add Reference window, under Assemblies on the left side of the window, select Framework.

    3. Select System.ServiceModel, and then select OK.

    4. Save the solution by selecting File > Save All.

Add code to host the service

To host the service, you add code to do the following steps:

  1. Create a URI for the base address.
  2. Create a class instance for hosting the service.
  3. Create a service endpoint.
  4. Enable metadata exchange.
  5. Open the service host to listen for incoming messages.

Make the following changes to the code:

  1. Open the Program.cs or Module1.vb file in the GettingStartedHost project and replace its code with the following code:

    using System;using System.ServiceModel;using System.ServiceModel.Description;using GettingStartedLib;namespace GettingStartedHost{ class Program { static void Main(string[] args) { // Step 1: Create a URI to serve as the base address. Uri baseAddress = new Uri("http://localhost:8000/GettingStarted/"); // Step 2: Create a ServiceHost instance. ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress); try { // Step 3: Add a service endpoint. selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService"); // Step 4: Enable metadata exchange. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); // Step 5: Start the service. selfHost.Open(); Console.WriteLine("The service is ready."); // Close the ServiceHost to stop the service. Console.WriteLine("Press <Enter> to terminate the service."); Console.WriteLine(); Console.ReadLine(); selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); } } }}
    Imports System.ServiceModelImports System.ServiceModel.DescriptionImports GettingStartedLib.GettingStartedLibModule Service Class Program Shared Sub Main() ' Step 1: Create a URI to serve as the base address. Dim baseAddress As New Uri("http://localhost:8000/GettingStarted/") ' Step 2: Create a ServiceHost instance. Dim selfHost As New ServiceHost(GetType(CalculatorService), baseAddress) Try ' Step 3: Add a service endpoint. selfHost.AddServiceEndpoint( _ GetType(ICalculator), _ New WSHttpBinding(), _ "CalculatorService") ' Step 4: Enable metadata exchange. Dim smb As New ServiceMetadataBehavior() smb.HttpGetEnabled = True selfHost.Description.Behaviors.Add(smb) ' Step 5: Start the service. selfHost.Open() Console.WriteLine("The service is ready.") ' Close the ServiceHost to stop the service. Console.WriteLine("Press <Enter> to terminate the service.") Console.WriteLine() Console.ReadLine() selfHost.Close() Catch ce As CommunicationException Console.WriteLine("An exception occurred: {0}", ce.Message) selfHost.Abort() End Try End Sub End ClassEnd Module

    For information about how this code works, see Service hosting program steps.

  2. Update the project properties:

    1. In the Solution Explorer window, select the GettingStartedHost folder, and then select Properties from the shortcut menu.

    2. On the GettingStartedHost properties page, select the Application tab:

      • For C# projects, select GettingStartedHost.Program from the Startup object list.

      • For Visual Basic projects, select Service.Program from the Startup object list.

    3. From the File menu, select Save All.

Verify the service is working

  1. Build the solution, and then run the GettingStartedHost console application from inside Visual Studio.

    The service must be run with administrator privileges. Because you opened Visual Studio with administrator privileges, when you run GettingStartedHost in Visual Studio, the application is run with administrator privileges as well. As an alternative, you can open a new command prompt as an administrator (select More > Run as administrator from the shortcut menu) and run GettingStartedHost.exe within it.

  2. Open a web browser and browse to the service's page at http://localhost:8000/GettingStarted/.

    Note

    Services such as this one require the proper 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.

Service hosting program steps

The steps in the code you added to host the service are described as follows:

  • Step 1: Create an instance of the Uri class to hold the base address of the service. A URL that contains a base address has an optional URI that identifies a service. The base address is formatted as follows: <transport>://<machine-name or domain><:optional port #>/<optional URI segment>. The base address for the calculator service uses the HTTP transport, localhost, port 8000, and the URI segment, GettingStarted.

  • Step 2: Create an instance of the ServiceHost class, which you use to host the service. The constructor takes two parameters: the type of the class that implements the service contract and the base address of the service.

  • Step 3: Create a ServiceEndpoint instance. A service endpoint is composed of an address, a binding, and a service contract. The ServiceEndpoint constructor is composed of the service contract interface type, a binding, and an address. The service contract is ICalculator, which you defined and implement in the service type. The binding for this sample is WSHttpBinding, which is a built-in binding and connects to endpoints that conform to the WS-* specifications. For more information about WCF bindings, see WCF bindings overview. You append the address to the base address to identify the endpoint. The code specifies the address as CalculatorService and the fully qualified address for the endpoint as http://localhost:8000/GettingStarted/CalculatorService.

    Important

    For .NET Framework Version 4 and later, adding a service endpoint is optional. For these versions, if you don't add your code or configuration, WCF adds one default endpoint for each combination of base address and contract implemented by the service. For more information about default endpoints, see Specifying an endpoint address. For more information about default endpoints, bindings, and behaviors, see Simplified configuration and Simplified configuration for WCF services.

  • Step 4: Enable metadata exchange. Clients use metadata exchange to generate proxies for calling the service operations. To enable metadata exchange, create a ServiceMetadataBehavior instance, set its HttpGetEnabled property to true, and add the ServiceMetadataBehavior object to the Behaviors collection of the ServiceHost instance.

  • Step 5: Open ServiceHost to listen for incoming messages. The application waits for you to press Enter. After the application instantiates ServiceHost, it executes a try/catch block. For more information about safely catching exceptions thrown by ServiceHost, see Use Close and Abort to release WCF client resources.

Important

When you add a WCF service library, Visual Studio hosts it for you if you debug it by starting a service host. To avoid conflicts, you can prevent Visual Studio from hosting the WCF service library.

  1. Select the GettingStartedLib project in Solution Explorer and choose Properties from the shortcut menu.
  2. Select WCF Options and uncheck Start WCF Service Host when debugging another project in the same solution.

Next steps

In this tutorial, you learned how to:

  • Create and configure a console app project for hosting a WCF service.
  • Add code to host the WCF service.
  • Update the configuration file.
  • Start the WCF service and verify it's running.

Advance to the next tutorial to learn how to create a WCF client.

Tutorial: Create a WCF client

Tutorial: Host and run a basic Windows Communication Foundation service - WCF (2024)

FAQs

How do I run WCF service from command line? ›

The WCF service can only respond to clients if the Windows service is running. To start the service, right-click it in the SCM and select "Start", or type net start WCFWindowsServiceSample at the command prompt. If you make changes to the service, you must first stop it and uninstall it.

How do I create a simple WCF service? ›

Open the Visual Studio and create a “New Project” and select the WCF option where various WCF applications can be created, here I want a service application and select that choice and name the application and click ok. On Successful project creation, now Visual studio gives us the option for automatic code sample.

How do I run a WCF service in Visual Studio? ›

To step into a WCF Service
  1. Create a Visual Studio solution that contains both the WCF client and WCF service projects.
  2. In Solution Explorer, right-click the WCF Client project and then click Set as Startup Project.
  3. Enable debugging in the app.
Jan 11, 2024

How do I use WCF service in Windows form application? ›

Consuming WCF Service
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Project..." then Windows Forms Application.
  3. Provide the project a name, such as "ConsumingWCFServiceInWindowsApp" or another as you wish and specify the location.
  4. Rename Form.
Aug 28, 2019

How do I activate WCF service? ›

Activate Windows Communication Foundation (WCF)
  1. From the Start menu, select Administrative Tools > Server Manager.
  2. Select Add roles and features from the Dashboard.
  3. Select Next twice.
  4. Select Features.
  5. In the Features area, expand the: - . ...
  6. Under WCF Services select: - HTTP Activation.

How do I start a Windows service from the command line? ›

Use a command prompt
  1. To start a service, type: net start ServiceName.
  2. To stop a service, type: net stop ServiceName.
  3. To pause a service, type: net pause ServiceName.
  4. To resume a service, type: net continue ServiceName.
Jul 7, 2021

Is WCF still used? ›

Windows Communication Framework (WCF) may be deprecated in . NET 5/6+, but it doesn't mean your applications are going to be left out in the cold. Just like Web Forms and other . NET Framework technologies, your WCF applications will continue to work for a long time.

What is the difference between Web API and WCF service? ›

WCF was created to develop SOAP-based services and bindings. Since WCF is SOAP based, which uses standard XML schema over HTTP, it could lead to slower performance. WEB API is a better choice for simpler, light weight services. WEB API can use any text format including XML and is faster than WCF.

What is WCF and how does it work? ›

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

How do I access WCF service? ›

With the service running, right click the project that will contain the WCF client proxy and select Add > Service Reference. In the Add Service Reference Dialog, type in the URL to the service you want to call and click the Go button. The dialog will display a list of services available at the address you specify.

How do you check WCF service is running or not? ›

Testing WCF service using Test Client (wcftestclient.exe)
  1. Open Visual Studio command prompt and type wcftestclient then Enter.
  2. After pressing Enter, we get a GUI application of the WCF Test Client.
  3. Select File->Add Service and type the service endpoint url as address and click ok. ...
  4. Double click on Greeting Method.
Feb 14, 2011

What is the difference between WCF service and Web service? ›

Web services support only one protocol- HTTP and HTTPS during communication, but WCF supports more protocols like- HTTP, TCP, and MSMQ that can be extended for a comprehensive solution, reliable session, and transactions. It signifies WCF is more adaptable to work together for a variety of software.

How to create a WCF service? ›

Also, a basic understanding of C# will be helpful.
  1. Step 1: Creating a new WCF Service Application. First, open Visual Studio and create a new project. ...
  2. Step 2: Defining the Service Contract. ...
  3. Step 3: Implementing the Service Contract. ...
  4. Step 4: Configuring the Service. ...
  5. Step 5: Hosting and Testing the Service.

How do I install WCF service? ›

Windows Server 2016 / 2019
  1. In the Add Roles and Features Wizard, click Next until you get to the Features step.
  2. Expand the . NET Framework 4.7 Features item.
  3. Make sure that the WCF Services -> HTTP Activation feature is enabled.
  4. Click Next until the Install button is enabled.
  5. Click Install and continue with the wizard.

How do I add WCF service to my web application? ›

Add a WCF service reference
  1. In Solution Explorer, right-click the name of the project to which you want to add the service, and then select Add Service Reference. ...
  2. In the Address box, enter the URL for the service, and then select Go to search for the service.
Jul 29, 2024

How do I check my WCF service? ›

Test the Service

From the main menu, click DEBUG > Start Without Debugging. This starts the service and invokes the WCF Test Client window. The left pane shows the endpoint for your service and the operations that are exposed. In the left pane, double-click the Read() operation.

How do I use WCF service in console application? ›

Create Simple WCF Service And Host It On Console Application
  1. Open Visual Studio instance with "Run as administrator" and create one class library project. ...
  2. Now, right click on the project and add a new item. ...
  3. It will generate 2 files - interface and class file.
  4. Now, open the interface file and add a new function.
Dec 16, 2016

How do I access services from command line? ›

Command Prompt
  1. Click the Windows icon or round Windows button in the lower left corner.
  2. Type: Command Prompt.
  3. In the Command Prompt window, type Services. msc and press the Enter key.

Top Articles
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 5710

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.