[Reprint] windows Communication Foundation entry (part two)

Source: Internet
Author: User
Http://www.cnblogs.com/wayfarer/archive/2006/04/10/370957.html
[Thank you] Zhang Yi: clear window notes

Iii. Technical Elements of WCF
As a framework product based on SOA (Service Oriented Architecture), the most important thing about WCF is its ability to quickly create a service ). As shown in, a WCF Service consists of the following three parts:
 

1. Service Class: A class marked with [servicecontract] attribute, which may contain multiple methods. Except for marking some unique attributes of WCF, this class is no different from general classes.
2. HOST: can be an applicationProgramA process, such as a Windows Service, is an environment where the WCF Service runs.
3. endpoints: It can be either a group or a group. It is the core element of communication implemented by WCF.

A WCF Service is composed of an endpoints set. Each endpoint is the entry for communication. The client and server exchange information through the endpoint, as shown in:
 

We can see that an endpoint consists of three parts: Address, binding, and contract. This is easy to remember. We often call these three parts an endpoint ABCs.

Address is the network address of the endpoint. It indicates the destination of the message. Binding describes how to send messages, such as transmission protocols (such as TCP and HTTP) for sending messages, and security (such as SSL and SOAP message security ). Contract describes the content of a message and the message organization and operation methods, such as one-way, duplex, and request/reply. The meaning of ABCS In the endpoint is: where, how, and what. When a message is sent by WCF, the address is used to know the address of the message to be sent, the binding method is used to know how to send the message, and the contract method is used to know what the message is sent.

In WCF, The serviceendpoint class represents an endpoint. The endpointaddress, binding, and contractdescription types in the class correspond to the address, binding, and contract of the endpoint, for example:
 

The endpointaddress class also consists of Uri, identity, and optional headers sets, such:
 

The Uniqueness recognition of endpoint security is usually based on its URI value. To avoid URI duplication in some special cases, the identity is introduced to the URI to ensure the uniqueness of the endpoint address. Optional addressheader provides additional information, especially when multiple endpoints use the same URI address information, addressheader is very necessary.

The binding class contains the name, namespace, and bindingelement sets, such:
 

Binding name and namespace are the unique identifiers of service metadata (Service's metadata. The bindingelement describes the binding method for WCF communication. For example, securitybindingelement indicates that the endpoint uses the SOAP message security mode, while reliablesessionbindingelement indicates that the endpoint uses trusted messages to ensure message transmission. Tcptransportbindingelement indicates that the endpoint uses TCP as the communication transmission protocol. Each bindingelement has corresponding property values, which further describes the WCF communication method.

The order of bindingelement is also very important. The bindingelement set usually creates a stack for communication. The order of the stack is the same as that of the elements in the bindingelement set. The last binding element in the set corresponds to the bottom of the Communication stack, and the first binding element in the set corresponds to the top of the stack. The inbound message stream goes from the bottom to the stack, while the outbound message stream goes down from the top. Therefore, the binding element sequence in the bindingelement set directly affects the order in which the communication stack processes messages. Fortunately, WCF already provides a series of pre-defined bindings that can meet the needs of most cases, without the need for custom binding. Finally, the sequence of binding elements is carefully considered.

Contract is a set of operations that define the content of endpoint communication. Each operation is a simple message exchange ), for example, one-way or request/reply message exchange.

Class contractdescription is used to describe the contracts of WCF and their operation operations. In the contractdescription class, each contract operation has a corresponding operationdescription to describe the operation type, such as one-way or request/reply. Operationdescription also contains the messagedecription set to describe message.

In the WCF programming model, contractdescription is usually created in the interface or class that defines contract. This interface or class type is marked with servicecontractattribute, while its operation method is marked with operationcontractattribute. Of course, we can also use manual creation instead of CLR attribute.

Like binding, each contract also contains name and namespace, which is used for unique identification in the metadata of the service. In addition, contract also contains a set of contractbehavior. The contractbehavior type can be used to modify or extend the behavior of contract. Shows the composition of contractdescription:
 

Just like the icontractbehavior contained in contractdescription, WCF provides behavior, which can modify or expand some functions of the client and server. For example, servicemetadatabehavior is used to control whether the Service publishes metadata. Similarly, security behavior is used to control security and authorization, while transaction behavior controls transactions.

In addition to the contractbehavior mentioned above, it also includes servicebehavior and channelbehaivor. Servicebehavior implements the iservicebehavior interface, while channelbehaivor implements the ichannlebehavior interface.

Since WCF needs to manage the communication between the server and the client. For the server, WCF provides a servicedescription class to describe a WCF Service. for clients, WCF manages the channel used to send messages, the channeldescription class describes such a client channel.

Shows the composition of the servicedescription class:
 

We can useCodeYou can also use the attributeof wcfto create servicedescriptionobject, and use the tool svcutil.exe. Although it can be explicitly created, it is usually hidden as a part of the running service (as I will mention later ).

The structure of the channeldescription class is roughly the same as that of servicedescription, but it only contains a serviceendpoint, which indicates the target endpoint for the client to communicate through the channel. Of course, the behavior applied to channeldescription is also of the ichannelbehavior interface type ,:
 

Defining a WCF Service is very simple. Taking Hello world as an example, the defined service may be as follows:
Using system. servicemodel
[Servicecontract]
Public class helloworld
{
[Operationcontract]
Public void Hello ()
{
Console. writeline ("Hello World !");
}
}

System. servicemodel is a new class library provided by Microsoft for WCF for service-oriented programming. When developing a WCF application, you must first Add a reference to system. servicemodel. Most of the classes and interfaces in WCF are also under the namespace system. servicemodel.

We marked [servicecontract] For the helloworld class, which makes the Class a wcf Service, and the method Hello () indicates [operationcontract], it becomes an operation of the service.

However, it is recommended that you define an interface as a service, which makes the WCF Service more flexible. After all, an interface can be implemented by multiple classes at the same time, this means that multiple service contract implementations can be implemented. The preceding example can be modified:
[Servicecontract]
Public interface ihello
{
[Operationcontract]
Void Hello ();
}

The helloworld class implements the ihello interface:
Public class helloworld: ihello
{
Public void Hello ()
{
Console. writeline ("Hello World !");
}
}

Note that in the helloworld class that implements the ihello interface, you no longer need to mark servicecontractattribute and operationcontractattribute in the class and method.

As I mentioned earlier, a WCF Service must have a host as its running environment. This host can be ASP. NET, Windows service, or a common application, such as a console program. The following is the implementation of a host:
Using system. servicemodel
Public class hostapp
{
Static void main (string [] ARGs)
{
Servicehost host = new servicehost (typeof (helloworld), new uri ("http: // localhost: 8080/helloservice "));
Host. addserviceendpoint (typeof (ihello), new basichttpbinding (), "SVC ");
Host. open ();
Console. writeline ("Start your service .");
Console. readkey ();
Host. Close ();
}
}

In this hostapp, we created a servicehost object for helloworld. You can use it to create a WCF runtime, which is a group of objects responsible for receiving and sending messages. Servicehost can create a serivcedescription object and use serivcedescription and serciehost to create an endpointlistener for each serviceendpoint. The composition of servicehost is as follows:
 

The endpointlistener listener contains listening address, message filtering, and dispatch, which correspond to endpointaddress, contract, and binding in serviceendpoint. In endpointlistener, a channel stack is also included to send and receive messages.

Note that the type parameter passed during servicehost creation cannot be an interface. Therefore, here I pass in typeof (helloworld ). The addserviceendpoint () method of the servicehost class implements the function of adding an endpoint to the host. Its parameters are exactly three parts of the endpoint: Address, bingding, and contract. (In this case, ihello is servicecontract, and its method "hello" is operationcontract ).

Servicehost's open () method is used to create and open the service runtime, and after the program ends, I call the close () method to close this runtime. In this example, this method can not be called because the host is automatically disabled after the application ends. However, as a good programming habit, WCF still requires explicit calling of the close () method, because the essence of service runtime is to use channel to complete message transmission, when a service is enabled for running, the system occupies a channel. after calling the channel, We need to release the channel. Of course, we can also use the using statement to manage the release of servicehost resources.

After defining a WCF Service and running it on the host, how can it communicate with the client? In typical cases, both the server and client use the web service description language(wsdl.pdf. The client can generate the proxy code corresponding to the WCF Service through the tool svcutil.exe to complete message transmission ,:
 

Svcutil.exe is provided by the winfx runtime component SDK. If the SDK is correctly installed, you can find the application tool in it. The method for generating client proxy code is simple. First, you need to run the server service. Then run the following command in command line mode:
Svcutil http: // localhost: 8080/helloservice

In this way, two files output. CS and output. config are generated in the current directory. The former mainly includes a proxy object that implements the ihello interface. The proxy object is named helloproxy. The result of code generation is as follows:
[System. codedom. compiler. generatedcodeattribute ("system. servicemodel", "3.0.0.0")]
Public partial class helloproxy: system. servicemodel. clientbase <ihello>, ihello
{
Public helloproxy ()
{
}
Public helloproxy (string endpointconfigurationname ):
Base (endpointconfigurationname)
{
}
Public helloproxy (string endpointconfigurationname, string remoteaddress ):
Base (endpointconfigurationname, remoteaddress)
{
}
Public helloproxy (string endpointconfigurationname, system. servicemodel. endpointaddress remoteaddress ):
Base (endpointconfigurationname, remoteaddress)
{
}
Public helloproxy (system. servicemodel. channels. Binding binding, system. servicemodel. endpointaddress remoteaddress ):
Base (binding, remoteaddress)
{
}
Public void Hello ()
{
Base. innerproxy. Hello ();
}
}
(Note: This program runs in winfx 2006 February CTP)

The latter is the configuration information of the WCF Service, mainly including the address, binding, and contract configurations in the endpoint (ArticleI will introduce it in detail ).

Now the client can directly use the helloproxy object to communicate with the server:
Public class clientapp
{
Static void main (string [] ARGs)
{
Using (helloproxy proxy = new helloproxy ())
{
Proxy. Hello ();
}
Console. readkey ();
}
}

In addition to using the svcutil tool to generate client code, we can also use the code to complete the client. When a client sends a message to the server, its communication is based on the service endpoint. WCF provides the system. servicemodel. description. serviceendpoint class, which is created to implement communication between the two ends. Previously, I also mentioned that "for clients, WCF manages the channel used to send messages". Therefore, WCF provides channelfactory (its namespace is system. servicemodel. channel), which is used to create the runtime of the client ). Channelfactory corresponds to servicehost, which can create a channeldescription object. Different from servicehost on the server, the client does not need a listener because the client is often the initiator of the connection and does not need to listen for the incoming connection. Therefore, the channel stack of the client is created by channeldescription.

Both channelfactory and servicehost have channel stack, and the communication between the server and the client is completed through channel. This means that the client can send messages to the server using channelfactory. The client itself does not have a service object, so the Service proxy can be obtained through the channel. The client code can be modified as follows:
Using system. servicemodel;
Using system. servicemodel. description;
Using system. servicemodel. Channel

Public class clientapp
{
Static void main (string [] ARGs)
{
Serviceendpoint httpendpoint = new serviceendpoint (contractdescription. getcontract (typeof (ihello), new basichttpbinding (), new endpointaddress ("http: // localhost: 8080/helloservice/svc "));

Using (channelfactory <ihello> factory = new channelfactory <ihello> (httpendpoint ))
{
// Create an ihello Service proxy object;
Ihello service = factory. createchannel ();
Service. Hello ();
}
Console. readkey ();
}
}
(Note: This program runs in winfx 2006 February CTP)

For the above Code, we have two points to note:
1. if this method is used, the client can access the ihello interface. This also demonstrates the benefits of using interfaces to define services. In addition, to ensure convenient deployment, it is best to compile the interface of the service into an Assembly separately to facilitate deployment to the client.
2. The client must know the binding method and address of the server.

For the server, you can open the service directly in the browser and enter http: // localhost: 8080/helloservice in the address bar, for example:
 

Click the link: http: // localhost: 8080/helloservice? WSDL. We can see the WSDL of helloservice directly. I didn't use IIS here. In fact, WCF has built-in integration with httpsys, allowing any application to automatically become an HTTP listener.

Refer:
1. David Chappell, introducing windows Communication Foundation
2. Aaron skonnard, learn the ABCs of programming windows Communication Foundation
3. Microsoft Corporation, Windows Communication Foundation Architecture Overview

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.