Description
Windows Communication Foundation (WCF) is Microsoft's implementation of set of industry standards defining service interactions. WCF unifies the previous generations of Microsoft's technologies, offering the interoperability of ASP.NET web services, the extensibility of remoting and the productivity and power of Enterprise Services. Those who previously built multiple code bases to deal with web services and .NET remoting will surely come to appreciate the power of standardization that WCF offers. This article starts by explaining the motivation for service-orientation, and then continues to discuss in depth how to develop service-oriented applications using WCF. You will see how to take advantage of some of the built-in features such as service hosting. While the article shows how to use these features, it sets the focus on the 'why' and the rationale behind particular design decisions, often shedding light on poorly-documented and understood aspects. You will learn not only WCF programming, but also relevant design guidelines, best practices, and pitfalls. The objective of the training is not to just make you a WCF expert, but also a better software engineer.
|
|
Introduction to Service-Orientation
Most of the time we hear people around us, speaking about Service Oriented Architecture(SOA). And each one of them will have their own definition for SOA. To begin with, we will start understanding what exactly SOA is. The Organization for the Advancement of Structured Information Standards, better known as OASIS (http://www.oasis-open.org), provides this official definition in its Reference Model for Service Oriented Architecture:
|
|
To elaborate, SOA relies on the ability to access chunks of business functionality, potentially owned by different applications, departments, companies, or industries.
Enterprise Application Development Approach
We generally follow any of the below listed approaches, for the development of Enterprise Applications:
- Object Oriented Programming
- Component Oriented Programming
- Service Oriented Programming
There is a common goal behind all three of the above mentioned approaches i.e., Encapsulation and re-use. We gradually shifted from OOP to SOA, as developers progressed building more complex enterprise systems. Now, let us look at the in-depth details which made us to shift from OOP to SOA.
Object Oriented Programming
With object-oriented programming, classes encapsulate functionality and provide code-reuse. To share classes between distinct applications or binaries, however, you have to copy the code as shown in the figure below:
Figure 1. Duplicating types between components
Component Oriented Programming
Component-oriented programming introduces the concept of sharing binaries that encapsulate reusable classes. Initially, this was limited to the same machine until distribution was made possible with technologies like COM and DCOM, CORBA, and later Enterprise Java Beans (EJBs) and .NET Remoting. Although these technologies accomplish distribution in different ways the result is the same-binary components are activated over process and machine boundaries.
Figure 2. Shared component containing shared types
Component-oriented programming has many limitations, but the most obvious is tight coupling to a specific technology. How can a Java client call a COM component? How can a .NET assembly invoke an EJB? It all boils down to protocols and messaging formats.
Service Oriented Programming
Invoking a remote component of any kind requires serializing a message and passing it across applicable process or machine boundaries. Bridge technologies and adapters exist to transform messages from one technology into another, so that when the message arrives it can be understood and processed. The reverse happens as responses are fed back to the caller. This approach is cumbersome, however, sometimes introducing multiple transformations between clients and components- and sometimes not even possible. Instead of exposing components directly, components can be accessed through service boundaries to alleviate some of this pain.
Figure 3. Exposing functionality through a service boundary
service-orientation delivers a solution to the problems of distributed computing by introducing the concept of contracts, policies, and interoperability. In that respect, applications can communicate with one another's services, without concern over the technology each employs. Also, service-orientation is an approach to development that implies the encapsulation of business components, data access, and data storage such that access is controlled through a top-level entry point. The package is a service, accessible over whatever protocols are supported, even if it lacks interoperability.
|
|
A service can be developed using any existing technology. It could be a serviced component exposed using Enterprise Services, a .NET Remoting component, an ASMX web service, or a WCF service. Any of these technologies can be useful in exposing the business logic in such a way that the client can reach that functionality at remote locations in a distributed environment, without communicating directly with business components. Serviced components are reached using DCOM over TCP, .NET Remoting components via RPC over TCP, ASMX web services via SOAP over HTTP etc.,
|
|
Overview of Windows Communication Foundation
WCF simplifies development of connected applications through a new service-oriented programming model. WCF supports many styles of distributed application development by providing a layered architecture. At its base, the WCF channel architecture provides asynchronous, untyped message-passing primitives. Built on top of this base are protocol facilities for secure, reliable, transacted data exchange and broad choice of transport and encoding options. To understand the need of WCF, we will go through a problem scenario and discuss about the solutions with/without WCF.
Problem Scenario
The following example illustrates some of the problems that WCF addresses. A car rental company decides to create a new application for reserving cars. The management expects the application to be able to communicate with other software systems that are already running inside and outside their company.

Figure 4. Car Rental Company expected architecture
Solution without WCF
The development team that implements the rental car application would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the requirements. Instead, the application would probably use multiple existing .NET Framework technologies, such as the following:
- ASP.NET Web services (ASMX). An option for communicating with the J2EE-based existing reservation application and with the partner applications across the Internet
- .NET Framework remoting. An option for communication with the call center application, because both are built on the .NET Framework.
- Enterprise Services. Used by the rental car reservation application for managing object lifetimes and defining distributed transactions.
- WSE. Could be used along with ASMX to communicate with the J2EE-based reservation application and with the partner applications. Because it implements more recently defined Web services agreements, known collectively as the WS-* specifications, WSE allows for more flexible Web services security, as long as all applications involved support compatible versions of these new specifications.
- Microsoft Message Queuing (MSMQ). Used to communicate with Windows-based partner applications that require guaranteed data delivery as well as decoupling of workloads and application lifetimes. The durable messaging that Message Queuing provides is typically the best solution for intermittently connected applications.
Built on .NET Framework, the rental car reservation application must use more than one of these communication technologies to meet its requirements. Although this is technically possible, the resulting application would be complex to implement and challenging to maintain.
Solution with WCF
With WCF, the solution is much easier to implement. As the figure shows, WCF can be used for all the situations previously described. Accordingly, the rental car reservation application can use this single technology for all of its application-to-application communication. The following shows how WCF addresses each of these requirements:
- Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.
- You can also configure and extend WCF to communicate with Web services using messages not based on SOAP, for example, simple XML formats like RSS.
- Performance is of paramount concern for most businesses. WCF is developed with the goal of being one of the fastest distributed application platform developed by Microsoft..
- To allow optimal performance when both parties in a communication are built on WCF, the wire encoding used in this case is an optimized binary version of an XML Information Set. Messages still conform to the data structure of a SOAP message, but their encoding uses a binary representation of that data structure rather than the standard angle-brackets-and-text format of the XML 1.0 text encoding. Using this option makes sense for communicating with the call center client application, because it is also built on WCF, and performance is an important concern.
- Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the rental car reservation application can use them with any of the other applications it communicates with.
- Because it supports a large set of the WS-* specifications, WCF helps provide reliability, security, and transactions when communicating with any platform that also supports these specifications.
- The WCF option for queued messaging, built on Message Queuing, allows applications to use persistent queuing without using another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity.

Figure 5. Solution for Car Rental Company problem with WCF
WCF addresses a range of challenges for communicating applications. Three things stand out, however, as the most important aspects of WCF:
- Unification of existing .NET Framework communication technologies.
- Support for cross-vendor interoperability, including reliability, security, and transactions.
- Explicit service orientation.
Now, you understood the need of Windows Communication Foundation to facilitate current and future requirements. Letz move a step ahead and try to understand more about WCF.
WCF Software Requirements
We'll now cover the software platform requirements for both developing and running .NET 3.0 applications. WCF is part of the .NET 3.0 Framework API that is fully integrated into the major release of Windows-Windows Vista. Microsoft is also making the .NET 3.0 Framework backward compatible for certain versions of Windows, specifically Windows XP Service Pack 2 and Windows 2003 Service Pack 1.
The following are the component requirements to run and develop .NET 3.0 and WCF-based applications:
- Windows 2003 Service Pack 1/ Windows XP Service Pack 2/ Windows Vista
- The .NET Framework 2.0 redistributable package (x86/x64/I64), which is part of Vista (this is an add-on for Windows 2003 and XP Service Pack 2)
- The .NET 3.0 Framework components, which are part of Vista (these are add-ons for Windows 2003 and XP Service Pack 2)
The development environment requires a few extra tools and, as a general recommendation, should be equipped with a bit more resources for the hardware-specifically RAM, CPU, and disk space:
- Windows 2003 Service Pack 1/ Windows XP Service Pack 2/ or Windows Vista
- The .NET Framework 2.0 redistributable package (x86/x64/I64), which is part of Vista
- The .NET Framework 2.0 SDK (x86/x64/I64)
- The Microsoft Windows SDK-formerly known as Platform SDK
- The .NET Framework 3.0 runtime components (RTC), which are already included in Windows Vista
- Recommended: IIS installation-not required with Visual Studio 2005 development web server
- Recommended: Microsoft Visual Studio 2005 Express Edition (or "larger" version-Pro, Suite, and so on)
- Recommended: The .NET Framework 3.0 Development Tools for Visual Studio
|
|
WCF Architecture
The following graphic illustrates the major layers of the Windows Communication Foundation (WCF) architecture.

Figure 6. WCF Architecture
Contracts and Descriptions
Contracts define various aspects of the message system. The data contract describes every parameter that makes up every message that a service can create or consume. The message contract defines specific message parts using SOAP protocols, and allows finer-grained control over parts of the message, when interoperability demands such precision. The service contract specifies the actual method signatures of the service, and is distributed as an interface in one of the supported programming languages, such as Visual Basic or Visual C#.
Policies and bindings stipulate the conditions required to communicate with a service. For example, the binding must (at a minimum) specify the transport used (for example, HTTP or TCP), and an encoding. Policies include security requirements and other conditions that must be met to communicate with a service.
Service Runtime
The service runtime layer contains the behaviors that occur only during the actual operation of the service, that is, the runtime behaviors of the service. Throttling controls how many messages are processed, which can be varied if the demand for the service grows to a preset limit. An error behavior specifies what occurs when an internal error occurs on the service, for example, by controlling what information is communicated to the client. (Too much information can give a malicious user an advantage in mounting an attack.) Metadata behavior governs how and whether metadata is made available to the outside world. Instance behavior specifies how many instances of the service can be run (for example, a singleton specifies only one instance to process all messages). Transaction behavior enables the rollback of transacted operations if a failure occurs. Dispatch behavior is the control of how a message is processed by the WCF infrastructure.
Messaging
The messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels operate on messages and message headers. This is different from the service runtime layer, which is primarily concerned about processing the contents of message bodies.
There are two types of channels: transport channels and protocol channels.
Transport channels read and write messages from the network (or some other communication point with the outside world). Some transports use an encoder to convert messages (which are represented as XML Infosets) to and from the byte stream representation used by the network. Examples of transports are HTTP, named pipes, TCP, and MSMQ. Examples of encodings are XML and optimized binary.
Protocol channels implement message processing protocols, often by reading or writing additional headers to the message. Examples of such protocols include WS-Security and WS-Reliability.
Hosting and Activation
In its final form, a service is a program. Like other programs, a service must be run in an executable. This is known as a self-hosted service.
Services can also be hosted, or run in an executable managed by an external agent, such as IIS or Windows Activation Service (WAS). WAS enables WCF applications to be activated automatically when deployed on a computer running WAS. Services can also be manually run as executables (.exe files). A service can also be run automatically as a Windows service. COM+ components can also be hosted as WCF services.
WCF Terminology
Services
WCF applications expose functionality through services. A service is a Common Language Runtime (CLR) type that encapsulates business functionality and exposes a set of methods that can be accessed by remote clients. In order for a regular CLR type to be considered a service it must implement a service contract.
A service contract is defined by applying the ServiceContractAttribute to a class or interface. When applied to a class, the class becomes a service type. When applied to an interface, any class that implements the interface becomes a service type. In either case, methods exposed by the class or interface must be decorated with the OperationContractAttribute to be considered part of the service contract. Methods with this attribute are considered service operations. A service type must be hosted before clients can invoke service operations.
Hosting
Service functionality is made available at runtime through a host process-any managed process will do the trick. Many hosting options are available for WCF services,including:
- Self-hosting
This includes console applications, Windows Forms or WPF applications, or Windows services. - Internet Information Services (IIS)
Services can be hosted alongside other ASP.NET applications, for example. - Windows Activation Service (WAS)
This is similar to IIS hosting but is only available to IIS 7.0.
Endpoints
When the ServiceHost opens a communication channel for a service, it must expose at least one endpoint for the service so that clients can invoke operations. In fact, endpoints are the key to invoking service functionality. An endpoint describes where services can be reached, how they can be reached, and what operations can be reached.
Thus, endpoints have three key parts:
- Address
Refers to the URI where messages can be sent to the service. - Binding
Bindings indicate the protocols supported when messages are sent to a particular address. - Contract
Each address supports a specific set of operations, as described by a service contract.
The ServiceHost is provided with a list of endpoints before the communication channel is opened. These endpoints each receive messages for their associated operations over the specified protocols.
Addresses
Each endpoint is associated with an address, identified by a URI. An address has a scheme, domain, port, and path in the following format: scheme://domain[:port]/[path].
The scheme indicates the transport protocol being used, such as TCP, named pipes, HTTP, or MSMQ. Respectively, the schemes for these protocols are net.tcp, net.pipe, http, and net.msmq. The domain refers to either a machine name or web domain. Sometimes localhost is used for communications on the same machine. The port can be specified to use a specific communication port other than the default for the protocol identified by the scheme. For example, HTTP defaults to port 80. Here are some examples of valid base addresses before specifying a path:
net.tcp://localhost:9000
net.pipe://mymachinename
http://localhost:8000
http://www.anydomain.com
net.msmq://localhost
A path is usually provided as part of the address to disambiguate service endpoints. The path does not usually include a filename for self-hosting, but with IIS a physical file is implicitly included in the address.
These are valid self-hosting addresses that include paths:
net.tcp://localhost:9000/ServiceA
net.pipe://mymachinename/ServiceB
http://localhost:8000/Services/ServiceA
http://www.mydomain.com/ServiceA
net.msmq://localhost/QueuedServices/ServiceA
When you add endpoints to a ServiceHost instance, you must specify a unique address for each endpoint. That means that you must vary at least one of the scheme, domain, port, or path specified.
Bindings
A binding describes the protocols supported by a particular endpoint, specifically, the following:
- The transport protocol, which can be TCP, named pipes, HTTP, or MSMQ
- The message encoding format, which determines whether messages are serialized as binary or XML, for example
- Other messaging protocols related to security and reliability protocols, plus any other custom protocols that affect the contents of the serialized message
There are a number of predefined bindings (called standard bindings) provided by the service model. These standard bindings represent a set of typical protocols representative of common communication scenarios.
Metadata
Once the ServiceHost is configured for one or more endpoints, and communication channels are open, service operations can be invoked at each endpoint. This is according to the protocols supported by each endpoint. Clients invoke service operations at a particular endpoint. To do so, they need information about the endpoint, including the address, the binding, and the service contract. Information about service endpoints is part of the metadata for a particular service. Clients rely on this metadata to generate proxies to invoke the service.
Metadata can be accessed in two ways. The ServiceHost can expose a metadata exchange endpoint to access metadata at runtime, or it can be used to generate a WSDL document representing the endpoints and protocols supported by the
Proxies
Clients communicate with services using proxies. A proxy is a type that exposes operations representative of a service contract that hides the serialization details from the client application when invoking service operations. For WCF applications, proxies are based on the service contract, so if you have access to the service contract definition, you can create a proxy instance to invoke the service. Before the proxy instance can be used to call service operations, it must be provided with information about one of the endpoints exposed for that service contract-there is a one-to-one relationship between proxy and endpoint.
Tools also exist to generate proxies and endpoint configurations from metadata. In this chapter, you will learn how to create a proxy manually, without generating metadata, and how to use proxy generation tools. In either case, the client must open a communication channel with the service to invoke operations. This channel must be compatible with the channel exposed by the ServiceHost for communications to work.







Humayun Kabir MamunPosted Sep 8, 2015, 3:31 AM
Nice...
Vid KPosted Feb 16, 2011, 10:39 PM
"System.ServiceModel.EndpointNotFoundException: Could not connect to http://localhost:8000/Customer/CustomerService. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8000. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:8000\r\n at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)\r\n at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)\r\n at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)\r\n --- End of inner exception stack trace ---\r\n at System.Net.HttpWebRequest.GetRequestStream()\r\n at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()\r\n --- End of inner exception stack trace ---\r\n\r\nServer stack trace: \r\n at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()\r\n at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)\r\n at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)\r\n at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)\r\n at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)\r\n at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)\r\n at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)\r\n at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)\r\n at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)\r\n\r\nException rethrown at [0]: \r\n at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)\r\n at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)\r\n at DemoInterfaces.ICustomer.SayHello(String name)\r\n at DemoClient.Program.Main(String[] args) in D:\\WCF2005\\WCF Changes\\DemoClient\\Program.cs:line 23"
shiva kumarPosted Jun 28, 2010, 6:36 PM
namasthe anna, hatsup to u for get atleast this much of knowledge.
naison garvasisPosted Mar 31, 2010, 1:08 AM
As always, very well explained. I had attended this session :).
vijay kumarPosted Feb 11, 2010, 8:03 AM
Iam new one to WCF. Its very use full to me. Thak you very much...
Abhishek RustogiPosted Dec 19, 2009, 5:29 PM
very Well Drafted for Begginers
sudalaimani shanmugamPosted Nov 16, 2009, 4:13 AM
Could not connect to http://localhost:8000/Customer/CustomerService. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8000.<!--Session data-->
Dick de ZeeuwPosted Oct 12, 2009, 11:03 AM
Hi Murali, great article. I have one question though. What if 2 client request for the same service at the same time. Are those executed one after the other of does WCF multithreading? Or do I need to configure that, and if yes how? Other question I have, how can I access the service from my website? Thanks in advance, Dick de Zeeuw
Nithin Mohan T KPosted Sep 17, 2009, 2:19 AM
Really thanks for your article. Was really informative and you have explained things in pretty simple way..
Rahul MohtaPosted Sep 8, 2009, 8:04 AM
Gr8 knowldege sharing
Ajith KumarPosted May 21, 2009, 4:22 AM
Excellent article. Good for a beginner like me.
Pramod TiwariPosted Apr 27, 2009, 4:38 PM
Cool Man keep it up.
Mahesh ChandPosted Apr 17, 2009, 8:49 AM
Great article. Well formatted and explained.
DotNetLearner LearnerPosted Apr 17, 2009, 7:31 AM
This is an absolutely wonderfully written article for a beginner like me. I looked up at so many resources to get me started but nothing was as concise and clear as this one. Thanks a lot.