) WCF Study Notes (1) -- Foundation of WCF

Source: Internet
Author: User
Tags msmq

Address: http://www.cnblogs.com/MeteorSeed/archive/2012/04/24/2399455.html

 

 

Directory

I. WCF and SOA

Ii. WCF Model

Iii. WCF Architecture

Four encoding specifications

IWCFAndSOA

SOA is a way to organize enterprise software by providing a service appearance for all software and publishing the WSDL of these services in a centralized place. It uses clearly defined interfaces to transmit messages across boundaries to allow multiple autonomous services to work together. The real value of SOA is: allow developersCodeExtracts the implementation of common basic functions, and pays more attention to the business logic and required functional features. Developing SOA applicationsProgramWe can decouple the service code from the client's technology and platform. It is also irrelevant to concurrency management, transaction propagation and management, as well as communication reliability, protocols, and modes.

The four main design principles of SOA and their advantages in WCF are as follows:

    • Boundary is clearEvery service in the SOA system must be limited to a specific boundary. A service boundary refers to a clear boundary between the public interface of a service and its internal implementation. The functions of the WCF Service are expressed through clearly defined interfaces. The only way for external callers to communicate with the WCF Service is through this interface, and the client cannot know the service implementation details, to hide and decouple information.
    • Services are autonomousAutonomous services should be independent of version, deployment, and installation issues without affecting the entire SOA system. Services do not depend on any external services or components. We can only implement the extended functions for WCF by writing new interfaces.
    • Adopt standard contract definitions and communication protocolsServices communicate through contracts rather than implementation. Service Contract definitions and communication protocols are industry standards. WCF supports common protocols and mainstream encoding formats.
    • The service is self-explanatory.The service content must be self-explanatory, and the service must tell the client service functions in some way.WCF provides a strongly typed contract and generates a WSDL document based on the binding.

The above principles are abstract. To better design SOA programs, we should abide by the following principles:

    • Services are secureSecure Communication is required between the service and the client.
    • Services must be in the same status in the systemWhen a client request is executed, partial replacement conditions are prohibited, that is, the system must maintain a consistent state after providing the service to the client. If an error occurs, the system status should not be partially affected, must be restored to a consistent state.
    • Services are thread-safeThe service must be designed to be thread-safe in order to maintain multi-thread concurrent access.
    • The service is reliable.The client determines whether the Service has received messages.
    • The service is robust.The service and its error separation can prevent the error from affecting the service itself or other services.

The optional principles are as follows:

    • Services are platform-independentThe service should be called by any client without considering the Client technology.
    • Service scale is unchangeableThe Service Code should be the same regardless of the number of clients or the service load.
    • Services are availableThe service is always able to accept client requests without stopping them.
    • Services are responsive and limited.When the service starts to process client requests, the client cannot wait too long. Any operation performed by the service should be as short as possible, so it cannot take too much time to process client requests.

The infrastructure in Microsoft's WCF framework solves the majority of the above principles, allowing us to refocus on the business logic layer. The charm of service-oriented technologies has prompted more and more developers to invest in it.

Ii. WCF Model

The architecture of WCF is as follows:

The client and server models of WCF are as follows:

1 Address

Each service in WCF has a unique address. The address includes the service location and transmission protocol (transmission style ). The service location includes the target machine name, site, network, port, pipeline or queue, and an optional specific path or Uri.

The common address format is [base address]/[Optional URI], for example, "net. TCP: // localhost: 8081/myservice ".

The common format of the base address is [Transfer Protocol]: // [machine name or domain name] [: Optional port], as shown in"Net. TCP: // localhost: 8081".

WCF supports multiple transmission styles:

    • HTTPHTTP and HTTPS protocols are used for transmission. The default port number is 80.
    • TCPUseNet. tcp for transmission. The default address is 808.
    • Peer Network (peer network)Net. P2P is used for transmission.Windows equivalent network transmission mechanism.
    • IPC (internal process Communication)Net. pipe is used for transmission. The windows named pipe mechanism can only receive calls from the same machine, and each machine can only open one named pipe.
    • MSMQNet. MSMQ is used for transmission.WindowsMSMQ mechanism. The queue name must be specified. If it is a private queue, the queue type must be specified.

2 bind

Binding standardizes the combination of communication modes and interaction modes, and reasonably combines these communication features. A binding encapsulates a combination of options such as transmission protocol, message encoding, reliability, security, transaction propagation, and interoperability to keep them consistent.

WCF defines six common bindings:

    • Basic bindingByThe basichttpbinding class is provided to publish the WCF Service as a web service.
    • TCP bindingByThe nettcpbinding class provides TCP communication and supports multiple features, including reliability, transaction, security, and optimization of communication between WCF. The disadvantage is that the client must use WCF.
    • IPC bindingByThe netnamedpipebinding class provides the ability to use Named Pipes for communication on the same machine for transmission. It supports features similar to TCP binding and is the best binding for performance and security.
    • Web Service bindingByThe wshttpbinding class is provided. ws binding uses HTTP or HTTPS for transmission and provides various features such as reliability, transaction and security. These features follow the WS-* standard, this binding is designed for interoperability with systems that support the WS-* standard.
    • WS bidirectional bindingByThe wsdualhttpbinding class provides two-way communication.
    • MSMQ bindingByThe netmsmqbinding class is provided for transmission using MSMQ.

The commonly used binding protocols and encoding formats are as follows:

Name Transmission Protocol Encoding format Interoperability
Basichttpbinding HTTP/https Text, MTOM Yes
Nettcpbinding TCP Binary No
Netnamedpipebinding IPC Binary No
Wshttpbinding HTTP/https Text, MTOM Yes
Wsdualhttpbinding HTTP Text, MTOM No
Netmsmqbinding MSMQ Binary No

Note: Binary encoders used for binding TCP, IPC, and MSMQ are proprietary to WCF. Do not try to write a custom Parser for other platforms.

3. Contract

All the services in WCF are published as contracts, and the contracts have nothing to do with the platform. They are the standard way to describe service functions. WCF includes four types of contracts:

    • Service ContractDescribes the service operations that the client can perform.
    • Data contractDefines the data type that interacts with the service.
    • Incorrect contractDefines the errors thrown by the Service, as well as the way the service handles errors and transmits errors to the client.
    • Message contractThe message contract allows the service to directly interact with the message, which is used to customize the proprietary Message format. It also means that the context of your own application is not a common usage because it increases the complexity of the Code.

4 endpoints

An endpoint consists of three elements: Address, binding, and contract. An endpoint is a structure used to send and receive messages,An endpoint is a real interface that contains all the information required for an object interface.Each service must expose at least one business endpoint. Each endpoint has only one contract. All endpoints on a service contain a unique address, while a single service can publish multiple endpoints. These nodes can use the same or different bindings to publish the same or different contracts.

5. Metadata

The metadata of the Service describes the features of the service. external entities need to understand these features to communicate with the service. The service metadata includes XML, schema documents (data protocols used to define services), and WSDL documents (used to describe services ). After metadata is enabled, WCF automatically generates service metadata by checking the service and its endpoints.

6. Context

The WCF context combines the service host with the context that exposes the local CLR type as a service,Context is the core execution scope of a service instance. The context can be empty, that is, it does not contain any service instance.

7 host

The WCF Service class cannot exist out of thin air. Each WCF Service class must be hosted in a host process. A single host process can host multiple services, and the same service type can also be hosted in multiple host processes. if the service and client reside in the same process, it is called in-process hosting. Common hosts are as follows:

    • Web Site
    • Windows Forms applications
    • Windows Services
    • Windows activation Service (was)

The architecture of the WCF host is as follows:

Each. Net host process contains multiple application domains. Each application domain contains zero to multiple host instances. Each service host instance is dedicated to a special service type. Therefore, to create a host instance is to register a service host instance that contains all endpoints for the host machine type corresponding to the base address. Each service host instance has no to multiple contexts. One context can be associated with zero or one service instance.

8 proxy

WCF does not allow the client to directly interact with the service. The client uses a proxy to forward the call to the service. Even if the object is local, WCF still uses the remote programming model instantiation method and uses a proxy.

Iii. WCF Architecture

(1) channel stack Model

WCF channel model:

No matter where the other side of the interaction is located, WCF establishes a complete message pipeline for message sending and receiving. This message pipeline becomes a channel stack. Each channel component in the channel Stack has the opportunity to process messages, and the entire channel stack can be edited and inserted. This ensures that the WCF channel model has great flexibility. In addition, the WCF channel model is completely isolated from the upper-Layer Program, and any service/client can be easily configured to different channel models. The channel model can be divided into two parts: protocol channel and transmission channel. A channel stack can have any number of protocol channels, but generally only one transmission channel. The transmission channel is responsible for encoding messages and sending them to the remote end. The call stack encoder is used for encoding. Generally, protocol channels are responsible for maintaining non-business logic functions of messages, including transactions, logs, reliable messages, and security. Developers can customize protocol channels and insert them into channel stacks. A channel stack must contain at least one transmission channel and encoder. The transmission channel is responsible for encoding and sending messages. (The transmission channel will try to find the encoder from the bindingcontext object. If no encoder is found, the default encoder will be used. After the message encoding is completed, the transmission channel is responsible for sending the message to the remote end, different transmission channels use different transmission protocols, such as HTTP, TCP, and IPC .)

The architecture of the WCF system is based on the interception mechanism. The interaction between the proxy and the client means that the WCF is always between the service and the client. It intercepts all calls and processes before and after the call. When the call stack frame is serialized to the message and the message is passed down through the channel chain, WCF starts to intercept the message. The channel is equivalent to an interceptor to execute a specific task. Each client channel executes pre-processing of message calls. The composition and structure of a chain mainly depend on binding. The last channel of the client is the transmission channel, which sends messages to the host according to the configured transmission mode. On the host end, messages are also transmitted through the channel chain, which performs pre-processing on the message before calling the host end. The first channel at the host end is the transmission channel that receives transmitted messages. The subsequent channels execute different tasks. The last channel at the host end is responsible for passing messages to the distributor. The distributor converts messages to a stack frame and calls the service instance. In fact, the service will be called by the local client-distributor. The interceptor of the client and the server ensures that they can obtain the runtime environment for them to perform correct operations.

The service instance executes the call and returns the control to the distributor. The distributor is responsible for converting the returned values and error messages into one returned message. The distributor obtains control. The execution process is the opposite: the distributor transmits messages through the Host channel and executes the processing after the call, such as management transactions and encryption. To perform the processing after the client calls, including decryption, decoding, committing, or canceling transactions, the transmission channel sends the returned messages to the client channel. The last channel passes the message to the proxy. The proxy converts the returned message to the stack frame and then returns the control to the client.

(2) message exchange mode

6 message exchange modes defined by WCF:

1. Request-response mode

The client sends a request to the server, waiting for the server's response. The waiting time is a predefined time and the most common mode. In WCF, [servicecontact] and [operationcontract] are defined on the interface to indicate the request and Response Details.

2Ticket message processing mode

Send messages from the client to the server in one direction. The server only processes the messages but does not return the processing results. The biggest value of this mode is its ability to implement asynchronous communication and ensure the messaging environment. By using the ticket mode, MSMQ can be used to send messages. By calling [Operationcontract] Isoneway is set to true to realize the ticket mode.

3Duplex message processing mode

The client and the server call each other, and the roles of the client and the server are also changing. To complete the callback, the server must know the method signature of the callback operation, and the callback operation will appear on both the client and the server. To implement the duplex mode in WCF, You need to describe in its binding information that the method signature implemented on the client must be defined at the service layer, and these methods must be implemented on the client, in this way, the server can call them.

4Stream Mode

The client initiates a request to request a very large amount of data. The service divides the data into small pieces and sends these data blocks to the client one by one in the order of use. In this mode, a data request is followed by multiple responses. Each response contains a subset of all data, and the sender identifies the end of the data stream in the final message, so that the client does not need to wait for more data.

5. Publishing-subscription Mode

In the publish-subscribe mode, the publisher does not care about whether there are subscribers. It only cares about sending data from its own system. This mode indicates a driver method, that is, the publisher starts an event in the client application and the client responds to the event. Instead of directly supporting the publishing-subscription mode, WCF uses the same structure as the duplex mode to implement the publishing-subscription mode. The publishing-subscription mode is implemented through a subscription service, which saves the reference of the subscriber callback channel in the memory. When the service needs to send data to all subscribers, it cyclically accesses these subscribers and calls a method to send data. The polling method is not used here because the subscriber acts as the host and is waiting for the method called by the Service.

6. Implicit sequential call mode

In this mode, the client calls multiple operations of the server in a certain order. The implicit sequential call mode allows you to define the last called method in the logical sequence. After that, the client cannot call other methods. In WCF, [operationcontract] is used to define the call sequence of operations. If the isinitiating of a method is set to false, a session can be started. If isterminating is set to true, the method is called to end the session. (Another method is to use workflow .)

Four encoding specifications

    • The Service Code should be put into the class library instead of the Host Program.
    • Do not provide a constructor with parameters for the service type, unless the managed service is a clear Singleton service.
    • Enable reliability in related bindings.
    • Provide meaningful namespaces for the contract.
    • For LAN applications running on Windows XP or Windows Server 2003, it is best to use self-managed, rather than IIS hosting.
    • In Windows Vista and Windows Server 2008 or later, it is best to use was instead of self-managed.
    • Enable metadata exchange.
    • Name all endpoints in the client configuration file.
    • Write the configuration file as much as possible.
    • Do not copy the proxy code. You can break the proxy into a separate class library.
    • Disable and release the agent in time.

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.