WCF Hosting Fundamental

Introduction

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF we can build secure, reliable, transacted solutions that integrate across platforms. 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. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

Image

Features of WCF

  • Multiple Message Patterns
  • Service Metadata, Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions, Extensibility
  • AJAX and REST Support

Difference between WCF and Web Service

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

WCF Fundamental

Some fundamental concepts in WCF which are given below :-

1. EndPoint :-

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world. It contains three part …

  • Address
  • Binding
  • Contract
  • Address: – Address is just like as WCF URL where this WCF service is hosted .Client will use this URL to connect to the service.

http://localhost:4090/MyHostedService/ArthmeticOperation.svc

  • Binding :- Binding is used for  how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

A binding has several characteristics, including the following:-

  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) – Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) – Defines information to be used in the binding such as Security, transaction or reliable messaging capability
  • Contract :- Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

2. Binding

Simple definition for Binding describes how the client will communicate with service. We can understand with an example.

Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using

<endpoint address=”http://localhost:4090/ MyHostedService/ArthmeticOperation.svc”

contract=”IMathService”

binding=”wsHttpBinding”/>

<endpoint address=”net.tcp://localhost:4090/ MyHostedService/ArthmeticOperation.svc”

contract=”IMathService”

binding=”netTcpBinding”/>

Note :-  Always enable serviceMetadata httpGetEnabled= true;

3.Contracts

All services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF.

  1. Data Contract
  2. Service Contract
  3. Message Contract
  4. Fault Contract
  5. Data Contract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.

Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.

A data contract can be defined as follows:

  • It describes the external format of data passed to and from service operations
  • It defines the structure and types of data exchanged in service messages
  • It maps a CLR type to an XML Schema
  • It defines how data types are serialized and deserialized. It is a versioning system that allows you to manage changes to structured data

Note :- We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract andDataMember attribute.

  1. Service Contract

Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.

Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.

  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL

To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.

  1. Message Contract

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination. Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using ‘MessageHeader’ and ‘MessageBodyMember‘atttribute. Let us see the sample message contract definition.

WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination

  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

4. Fault Contract

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.

WCF Client

WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.

A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:

  1. Get the Proxy class and service end point information

Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.

  1. Call operations.

Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.

//Creating the proxy on client side
MyCalculatorServiceProxy.MyServiceProxy proxy 
= new MyCalculatorServiceProxy.MyServiceProxy();
 Console.WriteLine("Counter: " + proxy.MyMethod());
  1. Close the WCF client object.

After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.

WCF Architecture

Image

Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior – Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior – Tells how and whether metadata is available to outside world.
  • Instance Behavior – Specifies how many instance of the service has to be created while running.
  • Transaction Behavior – Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior – Controls how a message is processed by the WCF Infrastructure.

Messaging

- 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 are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels

Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

  • Protocol Channels

Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS

Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

  • Windows Activation Service

(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

  • Self-Hosting

WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

  • Windows Service

WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

WCF Hosting

In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.

  1. IIS Hosting
  2. Self-Hosting
  3. Windows Service
  4. Windows Activation Service
Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes