WCF Multi-layer Services Development with Entity Framework - Fourth Edition

5 (1 reviews total)
By Mike Liu
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Implementing a Basic HelloWorld WCF Service

About this book

This book will teach you all the essentials to develop WCF services using Entity Framework as the backend. You will be guided right through the creation of six WCF and Entity Framework solutions.

You will start off by creating, implementing, and hosting a basic HelloWorld WCF Service followed by deploying the service and publishing it to IIS. Next, you will learn how to create and test a layered service, and then enhance it further by adding a data access layer and exception handling. Next, you will be introduced to LINQ. Starting with the basics, you will then dive into the advanced concepts and features of LINQ to Entities, including Entity Framework, deferred execution, querying a view, and mapping a procedure. Finally, you will get to grips with the RESTful WCF services and security.

Publication date:
October 2014


Chapter 1. Implementing a Basic HelloWorld WCF Service

Windows Communication Foundation (WCF) is Microsoft's unified programming model to build service-oriented applications. It is built on Microsoft's .NET framework and unifies a broad array of distributed systems capabilities in a composable, extensible architecture that supports multiple transports, messaging patterns, encodings, network topologies, and hosting models.

In this chapter, we will first learn basic WCF concepts and then implement a simple WCF service from scratch. We will build a HelloWorld WCF service by carrying out the following steps:

  • Creating the solution and project

  • Defining the WCF service contract interface

  • Implementing the WCF service

  • Hosting the WCF service in IIS Express

  • Creating a client application to consume the WCF service


The basic WCF concepts

There are many terms and concepts surrounding WCF, such as address, binding, contract, endpoint, behavior, hosting, and channels. Understanding these terms is very helpful when using WCF, so let's first take a look at these terms.


The WCF address is a specific location for a service. It specifies the path where a particular message will be sent. All WCF services are deployed at a specific address, and they listen at that address for incoming requests.

A WCF address is normally specified as a URL, with its first part specifying the transport mechanism and the next part specifying the unique location of the service. For example, http://www.myweb.com/myWCFServices/SampleService.svc is an address for a WCF service. This WCF service uses HTTP as its transport protocol, and it is located on the server, www.myweb.com, with a unique service path of myWCFServices/SampleService.svc.


Bindings are used to specify the transport, encoding, and protocol details required for clients and services to communicate with each other. Bindings are what WCF uses to generate the underlying representation of the endpoint (an endpoint is a place where clients can communicate with a WCF service; more details will follow). So, most of the details of the binding must be agreed upon by the parties that are communicating. The easiest way to achieve this for clients of a service is to use the same binding that the service uses.

A binding is made up of a collection of binding elements. Each element describes some aspect of how the service communicates with clients. A binding must include at least one transport binding element, at least one message-encoding binding element (which is provided by the transport binding element by default), and any number of other protocol binding elements. The process that builds a runtime out of this description allows each binding element to contribute code to that runtime.

WCF provides bindings that contain common selections of binding elements. These can either be used with their default settings, or the default values can be modified according to user requirements. These system-provided bindings have properties that allow direct control over the binding elements and their settings.

The following are some examples of system-provided bindings: BasicHttpBinding, WSHttpBinding, and NetTcpBinding. Each one of these built-in bindings has the predefined elements required for a common task and is ready to be used in your project. For instance, BasicHttpBinding uses HTTP as the transport to send SOAP 1.1 messages, and it has attributes and elements such as receiveTimeout, sendTimeout, maxMessageSize, and maxBufferSize. You can use the default settings of attributes and elements of BasicHttpBinding, or overwrite them as needed. We will explore all of the three bindings in this book.


A WCF contract is a set of specifications that defines the interfaces of a WCF service. A WCF service communicates with other applications according to its contracts. There are several types of WCF contract, such as service contract, operation contract, data contract, message contract, and fault contract. We define service contract and operation contract in the following sections of this chapter, and define more contracts throughout this book.

The service contract

A service contract is the interface of the WCF service. Basically, it tells us what the service can do. It can include service-level settings such as the name of the service, the namespace of the service, and the corresponding callback contracts of the service. Inside the interface, it can define a bunch of methods or service operations for specific tasks. A WCF service has to contain at least one service contract to service requests.

The operation contract

An operation contract is defined within a service contract. It defines the parameters and the return type of an operation. An operation can take data of a primitive (native) data type, such as an integer, as a parameter, or it can take a message, which should be defined as a message contract type. Just as a service contract is an interface, an operation contract is the definition of an operation. It has to be implemented in order for the service to function as a WCF service. An operation contract also defines operation-level settings such as the transaction flow of the operation, the direction of the operation (one-way, request/reply, or duplex callbacks), and the fault contract of the operation.

The message contract

If an operation contract needs to pass a message as a parameter or return a message, the type of these messages will be defined as message contracts. A message contract defines the elements of the message as well as any message-related settings, such as the level of message security and also whether an element should go to the header or to the body.

The data contract

Data contracts are the data types of the WCF service. All data types used by the WCF service must be described in the metadata to enable other applications to interoperate with the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements. If a WCF service uses only primitive (native) data types, it is not necessary to define a data contract.

The fault contract

In any WCF service operation contract, if an error is returned to the caller, the caller should be warned of that error. These error types are defined as fault contracts. An operation can have zero or more fault contracts associated with it.


Messages are sent between endpoints. Endpoints are places where messages are sent or received (or both), and they define all the information required for the message exchange. A service exposes one or more application endpoints (as well as zero or more infrastructure endpoints). A service can expose this information in the form of metadata that clients process to generate the appropriate WCF clients and communication stacks. When needed, the client generates an endpoint that is compatible with one of the service's endpoints.

A WCF service endpoint has an address, a binding, and a service contract (sometimes referred to as WCF ABCs).


A WCF behavior is a type or setting to extend the functionality of a WCF component. There are many types of behaviors in WCF, such as service behavior, binding behavior, contract behavior, security behavior, and channel behavior. For example, a new service behavior can be defined to specify the transaction timeout of the service, the maximum concurrent instances of the service, and whether the service publishes metadata. Behaviors are configured in the WCF service configuration file. We will configure several specific behaviors in the chapters that follow. We will learn how to extend a WCF service with behaviors in Chapter 13, Extending WCF Services.


The WCF service is a component that can be called by other applications. It must be hosted in an environment in order to be discovered and used by others. The WCF host is an application that controls the lifetime of the service. With .NET 3.0 and higher, there are several ways to host the service. We will explore various WCF hosting options in Chapter 2, Hosting the HelloWorld WCF Service.


As we have seen in previous sections, a WCF service has to be hosted in an application on the server side. On the client side, the client applications have to specify the bindings to connect to the WCF services. The binding elements are interfaces, and they have to be implemented in concrete classes. The concrete implementation of a binding element is called a channel. A binding element represents a configuration and a channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of one another to create the concrete implementation of the binding—the channel stack.

The WCF channel stack is a layered communication stack with one or more channels that process messages. At the bottom of the stack is a transport channel that is responsible for adapting the channel stack to the underlying transport (for example TCP, HTTP, SMTP, and other types of transport). Other channels provide a low-level programming model to send and receive messages.


The metadata of a service describes the characteristics of the service that an external entity needs to understand in order to communicate with the service. Metadata can be consumed by the ServiceModel metadata utility tool (SvcUtil.exe) to generate a WCF client proxy and the accompanying configuration that a client application can use to interact with the service.

The metadata exposed by the service includes the XML schema documents that define the data contract of the service and WSDL documents that describe the methods of the service.

Though WCF services always have metadata, it is possible to hide the metadata from outsiders. If you do so, you have to pass the metadata to the client side by other means. This practice is not common but it gives your services an extra layer of security. When enabled through the configuration settings from metadata behavior, metadata for the service can be retrieved by inspecting the service and its endpoints. The following configuration setting in a WCF service configuration file will enable metadata publishing for the HTTP transport protocol:

<serviceMetadata httpGetEnabled="true" />

WCF environments

WCF was first introduced in Microsoft's .NET Common Language Runtime (CLR) Version 2.0. The corresponding framework at that time was .NET 3.0. To develop and run WCF services, Microsoft .NET Framework 3.0 or above is required.

Visual Studio is Microsoft's IDE to develop WCF service applications. Visual Studio 2008 and above support WCF service application development.

The following table shows all of the different versions of the .NET runtimes, .NET frameworks, and Visual Studio versions, along with their relationships:


.NET framework


Visual Studio


.NET 4.5.1

.NET 4.5.2

Windows 8.1

Universal App

Type Script


CLR 4.0

.NET 4.5

Windows 8


Portable Class Libraries

2012 or above

.NET 4.0

Parallel Computing


Covariance and Contravariance

2010 or above

CLR 2.0

.NET 3.5 SP1


Entity Framework

LINQ to Entities

Cloud Computing

2008 or above

.NET 3.5





2008 or above



LINQ to Objects

.NET 3.0





.NET 2.0




2005 or above

CLR 1.0

.NET 1.1





.NET 1.0



Creating the HelloWorld solution and project

Now that we have a basic understanding of WCF concepts and terminologies, let's start building a simple HelloWorld WCF service. Before we can build the WCF service, we need to create a solution for our service project. We also need a directory in which we will save all the files. Throughout this book, we will save our project source codes in the C:\SOAwithWCFandEF\Projects directory. We will have a subfolder for each solution we create, and under this solution folder we will have one subfolder for each project.


You don't need to manually create these directories with Windows Explorer; Visual Studio will create them automatically when you create the solutions and projects.

Now, follow these steps to create our first solution and the HelloWorld project:

  1. Start Visual Studio 2013 (you can use Visual Studio Ultimate, Premium, or Professional throughout this book). If the Open Project dialog box pops up, click on Cancel to close it.

  2. Go to menu FILE | New | Project.... The New Project dialog window will appear, as follows:

  3. From the left-hand side of the window, expand Installed | Templates | Other Project Types and then select Visual Studio Solutions as the template. From the middle section of the window, select Blank Solution.

  4. At the bottom of the window, type in HelloWorld in the Name field and enter C:\SOAwithWCFandEF\Projects\ in the Location field. Note that you should not enter HelloWorld within the location, because Visual Studio will automatically create a new folder for us inside the Projects folder.

  5. Click on the OK button to close this window, and your screen should look like the following screenshot with an empty solution:

  6. Depending on your settings, the layout might be different. However, you should still have an empty solution in your Solution Explorer. If you don't see the Solution Explorer, navigate to VIEW | Solution Explorer or press Ctrl + Alt + L to bring it up.

  7. In the Solution Explorer, right-click on the solution and select Add | New Project… from the context menu. You can also go to FILE | Add | New Project… to get the same result. The following screenshot shows the context menu to add a new project:

  8. The New Project window should now appear on your screen. On the left-hand side of this window, select Installed | Visual C# as the template, and in the middle section of the window, select Class Library.

  9. At the bottom of the window, type in HelloWorldService in the Name field. Leave C:\SOAwithWCFandEF\Projects\HelloWorld in the Location field. Again, don't add HelloWorldService to the location, as Visual Studio will create a subfolder for this new project (Visual Studio will use the HelloWorld folder as the default base folder for all the new projects added to the solution). Refer to the following screenshot:

    You might have noticed that there is already a template for a WCF Service Application in Visual Studio 2013. For this very first example, we will not use this template. Instead, we will create everything by ourselves to understand the purpose of each template. This is an excellent way for you to understand and master this new technology. In the next chapter, we will use this template to create the project, so we don't need to manually type a lot of code.

  10. Now you can click on the OK button to close this window.

    Once you click on the OK button, Visual Studio will create several files for you. The first file is the project file. This is an XML file under our project's directory and it is called HelloWorldService.csproj.

    Visual Studio also creates an empty class file called Class1.cs. Later, we will change this default name to a more meaningful one.

    The window on your screen should now look like the one shown in the following screenshot:

We have now created a new solution and a new project. Next, we will develop and build this project as a new service. However, before we go any further, we need to do one more thing to this project. Click on the Show All Files button on the Solution Explorer toolbar as shown in the preceding screenshot. Clicking on this button will show all files and directories in your hard disk under your project's folder—even those items that are not included in the project. Make sure that you don't have the solution item selected, otherwise you cannot see the Show All Files button.

Lastly, in order to develop a WCF service, we need to add a reference to the System.ServiceModel assembly. Perform the following steps:

  1. In the Solution Explorer window, right-click on the HelloWorldService project and select Add | Reference… from the context menu. You can also right-click on References and select Add Reference… or go to PROJECT | Add Reference… to do this. The Reference Manager dialog window will appear on your screen as follows:

  2. Check the checkbox in front of System.ServiceModel from the Framework tab under Assemblies and click on OK.

Now in Solution Explorer, if you expand the references of the HelloWorldService project, you will see that System.ServiceModel has been added under References. Also, note that System.Xml.Linq is added by default. We will use this later when we query a database.


Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.


Defining the HelloWorldService service contract interface

In the previous section, we created the solution and the project for the HelloWorld WCF service. From this section onwards, we will start building the HelloWorld WCF service. First, we need to define the service contract interface. For this, perform the following steps:

  1. In the Solution Explorer, right-click on the HelloWorldService project and select Add | New Item… from the context menu. The Add New Item dialog window shown in the following screenshot will appear on your screen:

  2. On the left-hand side of the window, select Installed | Visual C# Items as the template, and from the middle section of the window, select Interface.

  3. At the bottom of the window, change Name from Interface1.cs to IHelloWorldService.cs.

  4. Click on the Add button.

Now an empty service interface file has been added to the project, which we are going to use as the service interface. Follow these steps to customize it:

  1. Add a using statement:

    using System.ServiceModel;
  2. Add a ServiceContract attribute to the interface. This will designate the interface as a WCF service contract interface:

  3. Add a GetMessage method to the interface. This method will take a string as the input and return another string as the result. It also has an attribute called OperationContract:

    string GetMessage(string name);
  4. Change the interface to public.

The final content of the file, IHelloWorldService.cs, should look as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace HelloWorldService
    public interface IHelloWorldService
        string GetMessage(string name);

Implementing the HelloWorldService service contract

Now that we have defined a service contract interface, we need to implement it. For this purpose, we will re-use the empty class file that Visual Studio created for us earlier and modify it to make it the implementation class of our service.

Before we modify this file, we need to rename it. In the Solution Explorer window, right-click on the Class1.cs file, select Rename from the context menu, and rename it as HelloWorldService.cs. Visual Studio is smart enough to change all the related files that are references to use this new name. You can also select the file and change its name from the Properties window.

Next, perform the following steps to customize the class file:

  1. Open the HelloWorldService.cs file.

  2. Make it implement IHelloWorldService implicitly as follows:

    public class HelloWorldService: IHelloWorldService
  3. Add a GetMessage method to the class. This is an ordinary C# method that returns a string. You can also right-click on the interface link and select Implement Interface to add the skeleton of this method.

    public string GetMessage(string name)
      return "Hello world from " + name + "!";

The final content of the HelloWorldService.cs file should look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldService
    public class HelloWorldService: IHelloWorldService
        public string GetMessage(string name)
            return "Hello world from " + name + "!";

Now, build the project. If there is no build error, it means that you have successfully created your first WCF service. If you see a compilation error such as 'ServiceModel' does not exist in the namespace 'System', this is because you didn't add the System.ServiceModel namespace reference correctly. Revisit the previous section to add this reference and you are all set.

Next, we will host this WCF service in an environment and create a client application to consume it.


Hosting the WCF service in IIS Express

HelloWorldService is a class library. It has to be hosted in an environment where client applications can access it. In this section, we will learn how to host it using IIS Express. Later in the next chapter, we will discuss more hosting options for a WCF service.

Creating the host application

There are several built-in host applications for WCF services within Visual Studio 2013. However, in this section, we will manually create the host application so that you can have a better understanding of what a hosting application is really like under the hood. In subsequent chapters, we will learn and use the built-in hosting application.

To host the library using IIS Express, we need to add a new website to the solution. Follow these steps to create this website:

  1. In the Solution Explorer, right-click on the solution HelloWorld and select Add | New Web Site… from the context menu (Always show solution must be enabled in DEBUG | Options and Settings... | Projects and Solutions in order to see the solution file). The Add New Web Site dialog window should pop up.

  2. Select Visual C# | ASP.NET Empty Web Site as the template and leave the Web location field set to File System, but change the default address to C:\SOAwithWCFandEF\Projects\HelloWorld\HostExpressServer and click on OK.

  3. Now in Solution Explorer, you have one more item (HostExpressServer) within the solution. It will look like the following:

  4. Next, we need to set the website as the startup project. In the Solution Explorer, right-click on the HostExpressServer website and select Set as StartUp Project from the context menu (or you can first select the website from Solution Explorer and then select the menu item WEBSITE | Set as StartUp Project). The HostExpressServer website should be highlighted in Solution Explorer, indicating that it is now the startup project.

  5. As we will host HelloWorldService from this website, we need to add a HelloWorldService reference to the website. In the Solution Explorer, right-click on the HostExpressServer website and select Add | Reference… from the context menu. The Reference Manager dialog box should appear, as shown in the following screenshot:

  6. In the Reference Manager dialog box, click on the Solutions tab and then click on Projects. Check the HelloWorldService project and then click on OK. You will see that a new directory (bin) has been created under the HostExpressServer website and two files from the HelloWorldService project have been copied to this new directory. Later on, when this website is accessed, the web server (IIS Express) will look for executable code in the bin directory.

Testing the host application

Now we can run the website inside IIS Express. If you start the HostExpressServer website by pressing Ctrl + F5 or by selecting DEBUG | Start Without Debugging in the menu, you will see an empty website in your browser with an error:

If you press F5 (or select DEBUG | Start Debugging from the menu), you might see a dialog saying Debugging Not Enabled. Choose the Run without debugging (equivalent to Ctrl + F5) option and click on the OK button to continue. We will explore the debugging options of a WCF service later. Until then, we will continue to use Ctrl + F5 to start the website without debugging.

IIS Express

At this point, you should have the HostExpressServer site up and running. This site actually runs inside IIS Express. IIS Express is a lightweight, self-contained version of IIS optimized for developers. This web server is intended to be used by developers only and has functionality similar to that of the Internet Information Services (IIS) server. It also has some limitations, for example, it only supports the HTTP and HTTPS protocols.

When a new website is created within Visual Studio, IIS Express will automatically assign a port for it. You can find your website's port in the Properties window of your website, as shown in the following screenshot:

IIS Express is normally started from within Visual Studio when you need to debug or unit test a web project. If you really need to start it from outside of Visual Studio, you can use a command-line statement in the following format:

"C:\Program Files\IIS Express\iisexpress" /path:c:\myapp\ /port:[your_port] /clr:v4.0

For our website, the statement should be as follows:

"C:\Program Files\IIS Express\iisexpress" /path:C:\SOAwithWCFandEF\Projects\HelloWorld\HostExpressServer /port:55859 /clr:v4.0


iisexpress.exe is located under your Program Files\ IIS Express\ directory. In an x64 system, it should be under your Program Files (x86)\ IIS Express\ directory.

Modifying the Web.config file

Although we can start the website now, it is only an empty site. Currently, it does not host our HelloWorldService website. This is because we haven't specified which service this website should host or an entry point for this website.

To specify which service our website will host, we can add a .svc file to the website. From .NET 4.0 onwards, we can also use the file-less (svc-less) activation service to accomplish this. In this section, we will take the file-less approach to specify the service.

Now, let's modify the Web.config file of the website to host our HelloWorldService (WCF service). Open the Web.config file of the website and change it to the following:

<?xml version="1.0"?>
  For more information on how to configure your ASP.NET application, please visit
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>

    <serviceHostingEnvironment >
        <add factory="System.ServiceModel.Activation.ServiceHostFactory" 
          <serviceMetadata httpGetEnabled="true"/>


Note that the system.serviceModel node is the only code that we have manually added to the Web.config file.

The httpGetEnabled behavior is essential because we want other applications to be able to locate the metadata of this service via HTTP. Without the metadata, the client applications can't generate the proxy and thus won't be able to use the service.

The following is a brief explanation of the other elements in this configuration file:

  • The configuration node is the root node of the file.

  • The system.serviceModel node is the top node for all the WCF service-specific settings.

  • The serviceHostingEnvironment node is used to specify the hosting environment.

  • The serviceActivations node is where you specify the service name and its relative address. This configuration element allows you to define the virtual service activation settings that map to your WCF service types. This makes it possible to activate services hosted in WAS/IIS without a .svc file.

  • Within the serviceBehaviors node, you can define specific behaviors for a service. In our example, we have specified one behavior, which enables the service metadata exchange for the service.

Starting the host application

Now, if you start the website by pressing Ctrl + F5 (don't use F5 or the menu option DEBUG | Start Debugging until we discuss these later), you will still see the same empty website with the same error. However, this time we have a service hosted within this website, so just append HostExpressServer/HelloWorldService.svc after the address (it should look something like http://localhost:55859/HostExpressServer/HelloWorldService.svc). Then, you will get the description of this service, that is, how to get the wsdl file of this service and how to create a client to consume this service. You should see a page similar to the one shown in the following screenshot:

Now, click on the WSDL link on this page and you will get the WSDL XML file for this service. The wsdl file gives all of the contract information for this service. In the next section, we will use this wsdl file to generate a proxy for our client application.


Creating a client to consume the WCF service

Now that we have successfully created and hosted a WCF service, we need a client to consume the service. We will create a C# client application to consume HelloWorldService.

In this section, we will create a Windows console application to call the WCF service.

Creating the client application project

First, we need to create a console application project and add it to the solution. Follow these steps to create the console application:

  1. In the Solution Explorer, right-click on the solution HelloWorld and select Add | New Project… from the context menu. The Add New Project dialog window should appear, as shown in the following screenshot:

  2. Select Visual C# | Console Application as the template, change the project name from the default value of ConsoleApplication1 to HelloWorldClient, and leave the Location field as C:\SOAwithWCFandEF\Projects\HelloWorld. Click on the OK button. The new client project has now been created and added to the solution.

Generating the proxy and configuration files

In order to consume a SOAP WCF service, a client application must first obtain or generate a proxy class.

We also need a configuration file to specify things such as the binding of the service, address of the service, and contract.

To generate these two files, we can use the SvcUtil.exe tool from the command line. You can follow these steps to generate the two files:

  1. Start the service by pressing Ctrl + F5 or by selecting the menu option DEBUG | Start Without Debugging (at this point, your startup project should still be HostExpressServer; if not, you need to set this to be the startup project).

  2. After the service has been started, open a command-line window, change the directory to your client application folder (that is, C:\SOAwithWCFandEF\Projects\HelloWorld\HelloWorldClient), and then run the command-line SvcUtil.exe tool with the following syntax (SvcUtil.exe might be in a different directory in your machine and you need to substitute 55859 with your service hosting port):

    "C:\Program Files\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcUtil.exe" http://localhost:55859/HostExpressServer/HelloWorldService.svc?wsdl /out:HelloWorldServiceRef.cs /config:app.config

You will see an output similar to that shown in the following screenshot:

Here, two files have been generated—one for the proxy (HelloWorldServiceRef.cs) and the other for the configuration (App.config).

If you open the proxy file, you will see that the interface of the service (IHelloWorldService) is mimicked inside the proxy class and a client class (HelloWorldServiceClient) is created to implement this interface. Inside this client class, the implementation of the service operation (GetMessage) is only a wrapper that delegates the call to the actual service implementation of the operation.

Inside the configuration file, you will see the definitions of HelloWorldService such as the endpoint address, binding, timeout settings, and security behaviors of the service.


You can also generate a proxy class within Visual Studio, which we will do later in this book, but behind the scenes the same SvcUtil.exe tool is used by Visual Studio to generate the proxy class.

In addition to generating a static proxy class at design time, you can also create a proxy dynamically at runtime or call the service through a Channel Factory instead of a proxy. Beware, if you go with the Channel Factory approach, you might have to share your interface DLL with the clients.

Customizing the client application

Before we can run the client application, we still have some more work to do. Follow these steps to finish the customization:

  1. When you switch to Visual Studio 2013, you will be asked to reload the App.config file, as it has been changed. Click on Yes to reload it.

  2. Add the proxy file to the project. In the Solution Explorer, first select the HelloWorldClient project and click on Show All Files to show all the files. Now, under the HelloWorldClient folder, you will see the proxy file (HelloWorldServiceRef.cs). However, this file is not yet included in the project. Right-click on it and select Include In Project to include it in the client project. You can also use the menu PROJECT | Add Existing Item… (or the context menu Add | Existing Item…) to add it to the project.

  3. Add a reference to the System.ServiceModel namespace. From the Solution Explorer, just right-click on the HelloWorldClient project, select Add | Reference…, and check System.ServiceModel under Assemblies | Framework. Then, click on the OK button to add the reference to the project.

  4. Modify program.cs to call the service. In program.cs, add the following line to initialize the service client object:

    var client = new HelloWorldServiceClient();


Using the default constructor on HelloWorldServiceClient means that the client runtime will look for the default client endpoint in the App.config file, which is present due to the use of SvcUtil.

Then, we can call the GetMessage method of our newly created object just as we would do for any other object:

Console.WriteLine(client.GetMessage("Mike Liu"));

Pass your name as the parameter to the GetMessage method so that it prints out a message for you.

Running the client application

We are now ready to run the client program.

First, make sure that the service host application, HostExpressServer, has been started. If you have stopped it previously, start it now (you need to set HostExpressServer as the startup project and press Ctrl + F5 to start it in the non-debugging mode, or you can just right-click on the HostExpressServer project and select View in Browser (Internet Explorer) from the context menu).

Then, from the Solution Explorer, right-click on the HelloWorldClient project, select Set as StartUp Project, and then press Ctrl + F5 to run it.

You will see an output as shown in the following screenshot:

Setting the service application to autostart

As we know we have to start the service host application before we run the client program, we can make some changes to the solution to automate this task, that is, to automatically start the service immediately before we run the client program.

To do this, in the Solution Explorer, right-click on solution, select Properties from the context menu, and you will see the Solution 'HelloWorld' Property Pages dialog box:

On this page, first select the Multiple startup projects option. Then, change the action of HostExpressServer to Start without debugging. Change HelloWorldClient to the same action.


HostExpressServer must be above HelloWorldClient. If it is not, use the arrows to move it to the top.

To test it, first stop the service and then press Ctrl + F5. You will notice that HostExpressServer is started first, and then the client program runs without errors.

Note that this will only work inside Visual Studio IDE. If you start the client program from Windows Explorer (C:\SOAwithWCFandEF\Projects\HelloWorld\HelloWorldClient\bin\Debug\HelloWorldClient.exe) without first starting the service, the service won't get started automatically and you will get an error message that says There was no endpoint listening at http://localhost:55859/HostExpressServer/HelloWorldService.svc.



In this chapter, we implemented a basic WCF service, hosted it within IIS Express, and created a command-line program to reference and consume this basic WCF service. At this point, you should have a thorough understanding of what a WCF service is under the hood. You will benefit from this knowledge when you develop WCF services using Visual Studio WCF templates.

In the next chapter, we will explore more hosting options so that you can choose an appropriate hosting method for your WCF services.

About the Author

  • Mike Liu

    Mike Liu studied Mathematics and Software Engineering at Nanjing University and Brandeis University, where he graduated with a Bachelor's degree and a Master's degree, respectively. He is a Sun Certified Java Programmer (SCJP), Microsoft Certified Solution Developer for Visual Studio 6.0, and Microsoft Certified Solution Developer for .NET. He has been working as a software engineer/architect on various platforms (DOS, Unix, and Windows) using C/C++, Java, VB/VB.NET, and C#.

    Mike started using C# for production development back in the year 2001 when C# was still in beta stage, and he is now working as a senior software engineer for an investment management firm in Boston, Massachusetts, US.

    Mike had his first book, MITT: Multi-user Integrated Table-processing Tool Under Unix, Beijing Hangtian University Press, published in 1993, and second book, Advanced C# Programming, Tsinghua University Press, published in 2003. The previous three versions of this book were published in 2008, 2010, and 2012.

    Browse publications by this author

Latest Reviews

(1 reviews total)
As usual, high-quality material.
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial