Overview of the Windows Communication Foundation (WCF) architecture and its main concepts. Code samples demonstrate WCF conventions, endpoints, and behaviors

Source: Internet
Author: User

Summary:Overview of the Windows Communication Foundation (WCF) architecture and its main concepts. The code example demonstrates WCF conventions, endpoints, and behaviors. Contents of this page

Brief introduction
WCF Basics
code example
Summary

Brief introduction

This document provides an overview of the Windows Communication Foundation (WCF) architecture. This article is intended to illustrate the main concepts in WCF and how they coordinate work. There are several code examples that explain these concepts in depth, but the code is not the focus of this document.

The following sections of this document are divided into the following two main elements:

    • WCF Fundamentals: Covers key concepts, terminology, and architectural components in WCF.

    • Code example: provides several short code examples to illustrate and materialize the concepts covered in the WCF Foundation.

Back to top of page
WCF Basics

A WCF service is a program that exposes a collection of endpoints . Each endpoint is a portal for communicating with the outside world.

A client is a program that exchanges messages with one or more endpoints. The client can also expose an endpoint to receive messages from the service in the mode of duplex message exchange.

These basics are described in more detail in the following sections.

End point

A service endpoint has an address , a binding , and a contract .

The address of the endpoint is the network address where the endpoint resides. The endpointaddress class represents a WCF endpoint address.

The binding of an endpoint specifies how the endpoint communicates with the outside world, including transport protocols (for example, TCP, HTTP), encoding (for example, text, binary files), and security requirements (for example, SSL, SOAP message Security), and so on. The binding class represents a WCF binding.

The contract for the endpoint specifies the content of the endpoint traffic, which is essentially an organized set of messages in the operation that has a basic message exchange pattern (MEPs), such as single-work, duplex, and request/reply. The ContractDescription class represents a WCF contract.

The ServiceEndpoint class represents an endpoint that has a endpointaddress, a binding, and a contractdescription that correspond to the address, bindings, and conventions of the endpoint, respectively (see Figure 1).

Figure 1. The endpoint for each service contains a endpointaddress, a binding, and a contract represented by ContractDescription.

EndpointAddress

EndpointAddress is actually a collection of URIs, an identity, and an optional header, as shown in 2.

The security identity of an endpoint is usually its URI, whereas in advanced scenarios you can use the identity Address property to explicitly set identities independently of URIs.

Optional headers are used to provide additional addressing information other than the endpoint URI. For example, the address header is useful for differentiating between multiple endpoints that share the same address URI.

Figure 2. EndpointAddress contains a uri,addressproperties that contains an identity and a Addressheaders collection.

Binding

A binding has a name, a namespace, and a collection of binding elements that can be written (Figure 3). The name and namespace of the binding uniquely identifies the binding in the metadata of the service. Each binding element describes one aspect of how the endpoint communicates with the outside world.

Figure 3. Binding class and its members

For example, Figure 4 shows a collection of binding elements that contain three binding elements. The existence of each binding element describes a portion of how it communicates with the endpoint. tcptransportbindingelement indicates that the endpoint communicates with the outside world using TCP as the transport protocol. reliablesessionbindingelement indicates that the endpoint uses reliable message processing to provide message delivery guarantees. securitybindingelement indicates that the endpoint uses SOAP message security. Each binding element typically has such a property: They further describe the details of how communication with the endpoint is. For example, Reliablesessionbindingelement has a assurances property that specifies the required message delivery guarantee, such as none, at least once, at most once, or just once.

Figure 4: an example of a binding with three binding elements

The order and type of binding elements in a binding is important: a collection of binding elements is used to build a communication stack that is sorted according to the order in which the binding elements are bound. The last binding element added to the collection corresponds to the bottom element of the communication stack, and the first binding element corresponds to the top element. The incoming message flows from the bottom up through the stack, while the outgoing message flows from top to bottom through the stack. Therefore, the order of the binding elements in the collection directly affects the order in which messages are processed by the communication stack component. Note that WCF provides a set of predefined bindings that you can use in most scenarios without having to define custom bindings.

Conventions

A WCF contract is a collection of operations that specify what the endpoint communicates with the outside world. Each operation is a simple message exchange, such as one-way or request/reply message exchange.

The ContractDescription class is used to describe WCF contracts and their operations. In ContractDescription, each contract operation has a corresponding operationdescriptionthat describes various aspects of the operation, such as whether the operation is one-way or request/reply. Each operationdescription also uses a messagedescriptions collection to describe the individual messages that comprise the operation.

With the WCF programming model, ContractDescription is typically created from interfaces or classes that define conventions. The type is annotated with ServiceContractAttribute , and the method that corresponds to the endpoint operation is annotated with OperationContractAttribute . You can also build a contractdescription manually without starting with a CLR type that uses attribute annotations.

A duplex contract defines two sets of logical operations: a set of actions that the service exposes to the client for invocation, and another set of actions that the client exposes to the service for invocation. The program model used to define the duplex contract divides each set of actions into a single type (each type must be a class or an interface) and uses the ServiceContractAttribute annotation to represent the contract for the service operation, referencing the contract that defines the client (or callback) operation. In addition, ContractDescription contains references to each type so that it can be made into a duplex convention.

Like bindings, each contract has a name and namespace that uniquely identifies the contract in the service metadata.

Each contract also has a Contractbehaviors collection, which is a module that modifies or extends the contract behavior. These behaviors are described in more detail in the next section.

Figure 5. ContractDescription class describes WCF conventions

Behavior

Behaviors are types that modify or extend the functionality of a service or client. For example, the metadata behavior implemented byServiceMetadataBehavior Controls whether the service publishes metadata. Similarly, security behavior controls impersonation and authorization, while transactional behavior controls registration and automatic completion of transactions.

Behavior also participates in the process of building the channel, which can be modified based on user-specified settings and/or other aspects of the service or channel.

A service behavior is a type that implements IServiceBehavior and applies it to a service. Similarly, the channel behavior is the type that implements the Ichannelbehavior and applies it to the client channel.

Service and Channel description

The servicedescription class is an in-memory structure that describes a WCF service, including the endpoints exposed by the service, the behavior applied to the service, and the type of implementation of the service (a class) (see Figure 6). ServiceDescription is used to create metadata, code/configuration, and channels.

You can build the ServiceDescription object manually. You can also create it from a type that uses a specific WCF attribute comment, which is a more common scenario. This type of code can be written manually, or it can be generated from a WSDL document using the WCF tools named SvcUtil.exe.

Although ServiceDescription objects can be created and populated explicitly, they are typically created in the background as part of running a service.

Figure 6. ServiceDescription Object Model

In the same way as the client,channeldescription describes a WCF client channel to a specific endpoint (Figure 7). The Channeldescription class has a collection of ichannelbehaviors, Ichannelbehaviors is the behavior that is applied to the channel. It also has a serviceendpoint that describes the endpoint (the channel communicates with the endpoint).

Note that unlike ServiceDescription, Channeldescription contains only one serviceendpoint that represents the target endpoint (the channel communicates with the endpoint).

Figure 7. Channeldescription Object Model

WCF Runtime

The WCF runtime is a set of objects that are responsible for sending and receiving messages. For example, formatting messages, applying security, transmitting and receiving messages using various transport protocols, and distributing received messages to the appropriate operations all occur in the WCF runtime. The following sections illustrate the main concepts of the WCF runtime.

News

A WCF message is a data exchange unit between a client and an endpoint. The message is essentially an in-memory representation of the SOAP message infoset . Note that the message is not bound to the text XML. In addition, depending on the encoding mechanism used, messages can be serialized using the WCF binary format, text XML, or any other custom format.

Channel

A channel is the core abstraction that sends a message to an endpoint and receives a message from the endpoint. Broadly speaking, there are two types of channels: The transport channel uses some form of transport protocol (such as TCP, UDP, or MSMQ) to handle sending or receiving opaque eight-byte streams. On the other hand, the Protocol channel implements a SOAP-based protocol by processing and possibly modifying the message. For example, a secure channel adds and processes a SOAP message header and may modify the body of the message by encrypting it. Channels are editable, so that one layer of channels can be on top of another, and the other layer can be on top of the third channel.

Endpointlistener

Endpointlistener is the runtime equivalent to ServiceEndpoint. ServiceEndpoint's endpointaddress, conventions, and bindings (representing location , content , and manner ) correspond to Endpointlistener's listening address, message filtering, and distribution, respectively , as well as the channel stack. The Endpointlistener contains the channel stack responsible for sending and receiving messages.

ServiceHost and ChannelFactory

The WCF service runtime is typically created in the background by calling Servicehost.open . ServiceHost(shown in Figure 6) drives the creation of servicedescription from the service type and populates the ServiceEndpoint collection of servicedescription with the endpoints defined in the configuration and/or code. ServiceHost then uses ServiceDescription to create a channel stack as a Endpointlistener object for each serviceendpoint in ServiceDescription.

Figure 8. ServiceHost Object Model

Similarly, on the client side, the client runtime is created by ChannelFactory , which is equivalent to the client's ServiceHost.

The ChannelFactory driver creates a channeldescription based on the type of contract, bindings, and EndpointAddress. It then uses the channel stack of the Channeldescription client.

Unlike the service runtime, the client runtime does not include Endpointlistener, because the client always initiates a connection to the service, so there is no need to "listen" for incoming connections.

Back to top of page
code example

This section provides code examples that show how to build services and clients. These examples are designed to make the above concepts more specific, rather than teach you about WCF programming.

Defining and implementing conventions

As mentioned earlier, the simplest way to define a contract is to create an interface or class and annotate it with ServiceContractAttribute , making it easy for the system to create a contractdescription.

When you use an interface or class definition convention, each interface or class method that is a contract member must be annotated with OperationContractAttribute . For example:

Using SYSTEM.SERVICEMODEL;//A WCF contract defined using an Interface[servicecontract]public interface imath{    [ OperationContract]    int Add (int x, int y);}

In this example, the implementation Convention is simply to create a class that implements IMath . The class becomes a WCF service class. For example:

The service class implements the Interfacepublic class mathservice:imath{public    int Add (int x, int y)    {retur n x + y; }}

Defining endpoints and starting services

Endpoints can be defined in code or configuration. In the following example, thedefineendpointimperatively method shows the simplest way to define an endpoint in code and start the service.

The

Defineendpointinconfig method displays the equivalent endpoint defined in the configuration (the configuration example follows the following code).

public class wcfserviceapp{public void defineendpointimperatively () {//create a service host for Mathservic        E ServiceHost sh = new ServiceHost (typeof (MathService));        Use the Addendpoint helper method to//create the ServiceEndpoint and add it//to the ServiceDescription Sh.          AddServiceEndpoint (typeof (IMath),//contract type new Wshttpbinding (),//one of the built-in bindings "Http://localhost/MathService/Ep1"); The endpoint ' s address//create and open the service runtime sh.    Open (); } public void Defineendpointinconfig () {//create a service host for mathservice ServiceHost sh = new        ServiceHost (typeof (MathService)); Create and open the service runtime sh.    Open (); }}<!--configuration file used by above code--><configuration xmlns= "http://schemas.microsoft.com/.    netconfiguration/v2.0 "> <system.serviceModel> <services>             <!--service element references the service type--<service type= "MathService" > <!--endpoint element defines the ABC's of the endpoint--and <endpoint address= "http: Localhost/mathservice/ep1 "binding=" Wshttpbinding "contract=" IMath "/> </service&gt      ; </services> </system.serviceModel></configuration>

Send a message to an endpoint

The following code shows two ways to send a message to the IMath endpoint. Sendmessagetoendpoint creates a hidden channel, which occurs in the background, while the Sendmessagetoendpointusingchannel example explicitly creates the channel.

The first example in Sendmessagetoendpoint uses a tool called svcutil.exe and the metadata of the service to generate a contract (IMath in this example), a proxy class that implements the contract (Mathproxy in this example). and the associated configuration (not shown here). Again, the contract defined by IMath specifies the content (that is, the action that can be performed), and the resulting configuration contains a binding ( way ) and an address ( location ).

The proxy class is used only to instantiate it and invoke the Add method. In the background, the proxy class creates a channel and uses that channel to communicate with the endpoint.

The second example in the following sendmessagetoendpointsusingchannel shows how to use ChannelFactory to communicate directly with an endpoint. In this example, the channel is created directly using Channelfactory.createchannel instead of the proxy class or configuration. Furthermore, theChannelFactory constructor takes these two pieces of information as arguments, rather than using configuration to define the address and bindings of the endpoint. The third part of the information (that is, the Convention) required to define an endpoint is passed in as type T.

Using System.servicemodel;//this contract is generated by svcutil.exe//from the service ' s Metadatapublic interface imath{ [OperationContract] public int Add (int x, int y) {return x + y;}} This class was generated by svcutil.exe//from the service ' s metadata//generated config was not shown Herepublic class Math Proxy:imath{...} public class wcfclientapp{public void Sendmessagetoendpoint () {//this uses a proxy class this was//        Created by svcutil.exe from the service ' s metadata mathproxy proxy = new Mathproxy (); int result = Proxy.    ADD (35, 7); } public void Sendmessagetoendpointusingchannel () {//this uses ChannelFactory to create the channel/ /you must specify the address, the binding and//the contract type (IMath) ChannelFactory factory=new Chann        Elfactory (New Wshttpbinding (), New EndpointAddress ("HTTP://LOCALHOST/MATHSERVICE/EP1")); IMath channel=factory. CreateChannel ();       int Result=channel.        ADD (35,7); Factory.    Close (); }}

Defining custom Behavior

Defining custom behavior requires only implementing IServiceBehavior (or Ichannelbehavior of client behavior). The following code shows an example behavior that implements IServiceBehavior. In Iservicebehavior.applybehavior, the code examines servicedescription and writes out the addresses, bindings, and conventions for each serviceendpoint, as well as ServiceDescription The name of each behavior in the.

This particular behavior is also a property (inherited from System.Attribute ) so that it can be applied declaratively, as shown below. However, the behavior does not have to be a property.

[AttributeUsageAttribute (AttributeTargets.Class, Allowmultiple=false, Inherited=false)]public CLA SS InspectorBehavior:System.Attribute, system.servicemodel.iservicebehavior{Public v  OID Applybehavior (servicedescription description, Collection behaviors) {Console.WriteLine ("--------       Endpoints---------"); foreach (ServiceEndpoint endpoint in description.           Endpoints) {Console.WriteLine ("--Endpoint"); Console.WriteLine ("Endpoint Address: {0}", Endpoint.           Address); Console.WriteLine ("Endpoint Binding: {0}", Endpoint. Binding.gettype ().           Name); Console.WriteLine ("Endpoint contract: {0}", Endpoint.           Contract.ContractType.Name);       Console.WriteLine ();       } Console.WriteLine ("--------Service behaviors--------"); foreach (IServiceBehavior behavior in deScription.           Behaviors) {Console.WriteLine ("--Behavior"); Console.WriteLine ("Behavior: {0}", Behavior. GetType ().           Name);       Console.WriteLine (); }   }}

Apply custom behavior

By adding an instance of the behavior to ServiceDescription (or to channeldescription on the client), all behaviors can be applied in a command manner. For example, to apply inspectorbehavioras a command, you could write the following code:

ServiceHost sh = new ServiceHost (typeof (MathService)); Sh. AddServiceEndpoint (       typeof (IMath),         new Wshttpbinding (),       "Http://localhost/MathService/Ep1");//add The behavior imperativelyinspectorbehavior behavior = new InspectorBehavior (); Sh. DESCRIPTION.BEHAVIORS.ADD (behavior); Sh. Open ();

In addition, the behavior inherited from System.Attribute can be applied declaratively to the service. For example, because InspectorBehavior inherits from System.Attribute, it can be applied declaratively, as follows:

[Inspectorbehavior]public class mathservice:imath{public   int Add (int x, int y)   {return x + y;}}
Back to top of page
Summary

The WCF service exposes a collection of endpoints, each of which is a portal for communicating with the outside world. Each endpoint has an address, a binding, and a contract (ABC). The address is where the endpoint resides, and the binding is the way The endpoint communicates, and the contract is the content of the endpoint traffic.

On the server side, ServiceDescription saves the collection of ServiceEndpoint, where each serviceendpoint describes an endpoint that the service exposes. Based on this description, ServiceHost creates a runtime that contains a endpointlistener for each serviceendpoint in ServiceDescription. The address, bindings, and conventions of the endpoint (representing location , content , and manner ) correspond to the Endpointlistener's listening address, message filtering and distribution, and the channel stack, respectively.

Similarly, on the client side, Channeldescription saves a serviceendpoint that communicates with the client. Based on the channeldescription,channelfactory, create a channel stack that can communicate with the service's endpoint.

Overview of the Windows Communication Foundation (WCF) architecture and its main concepts. Code samples demonstrate WCF conventions, endpoints, and behaviors

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.