[WCF programming] 3. WCF basics, wcf programming 3. wcf Basics

Source: Internet
Author: User
Tags msmq

[WCF programming] 3. WCF basics, wcf programming 3. wcf Basics
I. Service

A service is a set of public functions.

The service contains concepts such as language, technology, version, and framework. Only the specified communication mode is allowed for interactions between services.

External clients do not know the implementation details of the service. Therefore, the WCF Service usually describes available functions and possible communication modes of the service through metadata.

WCF does not allow the client to directly interact with the service. The client always uses a proxy to forward the call to the service. WCF allows the client to communicate with the service across execution boundaries, such as cross-application domains, processes, and even networks.

WCF requires the client to maintain a consistent programming model for both local and remote objects without considering the service location.

WCF uses proxy to call services for both local and remote objects, which greatly simplifies the programming model of the application. Using a proxy can intercept WCF requests and increase the value of WCF.

2. Address

In WCF, each service has a unique Address ).

The address contains two important elements: Service Location and transmission protocol.

The service location includes the target machine name, site, communication port, and MPs queue? (Or Queue), and an optional specific path or URI.

  • WCF supports the following transmission protocols
    • HTTP/HTTPS
      • The HTTP address can be transmitted over http/https. For example:
      • Http: // localhost: 81
      • The default port of the HTTP address is 80, while that of the HTTPS address is 443.
      • An HTTP address can share a port or even a machine.
    • TCP
      • The TCP address is transmitted using the net. tcp protocol? Usually, it also includes a port. For example:
      • Net. tcp: // localhost: 81/MyService
      • The default TCP port is 808.
      • Two TCP addresses can share one port.
    • IPC
      • The IPC (inter-process communication) address is transmitted using the net. pipe protocol. It uses the Windows named pipe mechanism.
      • In WCF, can a service with the naming Pipeline mechanism only accept services from the same machine? You must specify a specific local machine name or directly name it localhost to provide a unique identifier string for the pipeline name:
      • Net. pipe: // localhost/MyPipe
      • Only one named channel can be opened on the same machine. Therefore, the two named channel addresses cannot share one pipe name on the same machine.
    • Peer network (Peer network)
    • MSMQ
      • Is the MSMQ address transmitted using the net. msmq protocol? The message queue mechanism of Microsoft is used.
      • The queue name must be specified for the MSSQ address. If it is private? If a queue exists, the queue type must be specified. But for public queues, can the queue type be? Omitted:
      • Net. msmq: // localhost/private/MyService
      • Net. msmq: // localhost/MyService
    • Service bus
      • Windows Azure AppFabric service bus is transmitted over sb, http, or https
      • The Service Bus address must include the service namespace. For example:
      • Sb: // MyNameSpace.servicebus.windows.net/
  • Address communication usually uses the following format
    • [Base address]/[Optional URI]
  • The base address is generally in the following format:
    • [Transfer Protocol]: // [machine name or domain name] [: Optional port]
      • Example of address communication
        • Http: // localhost: 81
        • Http: // localhost: 81/MyService
        • Net. tcp: // localhost: 81/MyService
        • ......
Iii. Contract

All the services of WCF will be exposed as Contract)

The contract is independent of the platform. It is a way to describe service functions.

  • Service Contract)
    • The service contract describes the service operations that the client can perform.
  • Data Contract)
    • What is the data contract definition? Mutual data type.
    • WCF implicitly defines a built-in type as a data contract or a custom type as a data contract.
  • Fault Contract)
    • The error contract defines the error thrown by the Service and the server? How to handle and pass errors to the client
  • Message Contract)
    • The message contract allows the service to directly communicate? Message interaction can be typed or untyped.
    • If the other end of message interaction specifies some explicit (usually proprietary) message formats, which requires interoperability? In this scenario, message contracts are very useful.
4. Bind

Binding is the primary means for developers to control the interaction between WCF programs and other messages. In terms of function, it is bound to the stack object that creates the channel factory channel listener. Binding objects indirectly created by direct obfuscation is the main way for WCF to implement various message functions (such as transmission, security, and transaction. A binding encapsulates options such as transmission protocol, message encoding, communication mode, reliability, security, transaction propagation, and interoperability to keep them consistent.

  • Five common bindings
    • Basic binding
      • Corresponding BasicHttpBinding class
      • The basic binding function can publish the WCF Service as a traditional ASMX Web service, enabling the original client to collaborate with the new service.
    • TCP binding
      • For the NetTcpBinding class
      • TCP binding uses the TCP protocol to implement cross-machine communication in the Intranet. It supports multiple features, including reliability, transaction, security, and optimization of Inter-WCF communication, the premise is that both the client and service must use WCF.
    • IPC binding
      • Corresponding NetNamePipeBingding class
      • He uses the named pipe to communicate with the same machine for Transmission
      • This binding is the safest because it does not accept calls from outside the machine.
      • It is the best performance binding, because the IPC protocol is simpler than the TCP protocol
    • Web Service (WS) Binding
      • Corresponding to the WSHttpBinding class
      • WS binding using Http and Https? Row-based transmission provides multiple features (such as reliability, transaction, and security) for Intranet-based communication. These features comply with the WS-* standard.
      • This binding is used for interoperability with systems that support the WS-* standard.
    • MSMQ binding
      • Corresponding to the NetMsmqBinding class
      • Use MSMQ for transmission, used to support disconnected queue calls
  • Format and encoding
    • WCF standard binding

      • Name Transmission Protocol Encoding Interoperability
        BasicHttpBinding HTTP/HTTPS Text +
        NetTcpBinding TCP Binary -
        NetNamedPipeBinding IPC Binary -
        WSHttpBinding HTTP/HTTPS Text, MTOM +
        NetMsmqBinding MSMQ Binary -
    • Text Encoding usually allows the WCF Service (or client) to communicate with other services (or clients) Over HTTP without considering the technology used and the scope of communication and transmission.
    • The binary encoding format can achieve optimal performance through TCP, IPC, or MSMQ, but it only supports communication between WCF and WCF at the cost of sacrifice or operability.
  • Select binding
    • Select binding decision chart
      • .
  • Other bindings
    • WCF also provides three special cases: BasicHttpContextBindingg, WSHttpContextBinding, and NetTcpContextBinding.
    • Are context bindings inherited from their respective constants? Rules, and add support for the context protocol. The context protocol allows developers to transmit parameters to the service.
Vi. Hosting

Each WCF Service must be hosted in a Windows process. This process is called a host process)

A single host process can host multiple services. The same service type can also be hosted in multiple host processes.

  • Managed by IIS 5/6
    • The main advantage of hosting services on the IIS Web server is that the host process can be automatically started upon the first request from the client, and the life cycle of the host process can be managed using IIS 5/6.
    • The main disadvantage of IIS hosting is that you can only use the HTTP protocol. If it is IIS 5, it is also limited by ports, requiring all services to use the same port number.
  • Self-managed
    • Self-Hosting is a way for developers to provide and manage the lifecycle of host processes.
    • Use self-managed service when processes between the client and the server have clear boundaries. If the two are in the same process, you can use in-process hosting.
    • Can the self-managed service use any WCF transfer? And can use the advanced features of WCF.
  • WAS hosting
    • Is IIS 5/6 a Web server? Server instead of hosting the engine. Hosting a WCF server in IIS 5/6? The service is very unstable. You need to restart the Web server frequently? Use HTTP.
    • Is WAS common? The host engine can host websites (IIS 7 uses WAS by default? Website management), you can easily host the service and allow the use of any transfer? You can install and configure WAS separately without the same protocol as IIS 7? Start to use.
    • WAS is a system service, so you do not need to mention it? Start the host process. When the first call arrives, Will WAS block? Intercept this call message, start a working process and host the service, and then cancel the call? .
    • WAS can be used in WIndows Vista, Winodws Server 2008, Windows 7, and later versions.
  • Custom hosting in IIS/WAS
    • 1. To solve IIS 5/6 or? In WAS, the question of directly interacting with the host is raised by WCF? Provided hook called "host factory .? Directly use the Factory tag in the. svc file ,? You can customize the host creation class:
      <%@ ServiceHost Language="C#" Debug="true" Service="ch01.Service1" CodeBehind="Service1.svc.cs"Factory="MyServiceFactory" %>
    • 2. If you do not use the. svc file, you can also? Specify the host factory in the configuration file:
      <serviceActivations><add relativeAddress ="MyService.svc" service="MyService" factory="MyServiceFactory"/></serviceActivations>
    • 3. The host factory must inherit the ServiceHostFactory class ,? And override the CreateServiceHost () virtual method:
      • Class NyServiceFactory: ServiceHostFactory {protected override ServiceHost CreateServiceHost (Type serviceType, Uri [] baseAddress) {ServiceHost host = new ServiceHost (serviceType, baseAddress); // custom step return host ;}}
      • The CreateServiceHost () method is logically IIS or? The Main () method in the WAS hosting service can be used to enable? Use it to do the job.
  • Windows Server AppFabric
    • WAS is a general host engine. It does not actually know whether it is hosting a WCF Service or a website, and does not optimize the WCF Service.
    • To solve this problem, you can install the WAS extension, namely, Windows Server AppFabric.
    • Windows Server AppFabric requires IIS 7.5, which must be Windows 7, Winodws Server 2008 R2, And. NET 4.0.
    • Windows Server AppFabric is designed to provide additional configuration options such as monitoring, display, and time tracking for WCF or WF.
    • For the WCF development clerk, the most important Windows Server AppFabric function should be that it is not waiting for the first guest? The service can be automatically started when the user requests arrive. You can use Windows Server AppFabric to start the service automatically when the service is not dependent on the arrival of client requests.
  • Select host
    • Internet applications can be decided based on:
    • Intranet applications can be determined based on:

VII. endpoints

Services are related to addresses, bindings, and contracts.

The address defines the service location, the binding defines the service communication mode, and the contract defines the service content. It is called "ABC of the service".

WCF uses an endpoint to represent such a group of relationships. Endpoints are a mixture of addresses, bindings, and contracts.

Each endpoint contains these three elements, and the host is responsible for making the endpoint public.

Each service discloses at least one business endpoint, and each endpoint has only one service contract.

    • Configure endpoints as files

To configure an endpoint in management mode, you need to put the endpoint information in the configuration file of the managed process. For example, the following service definition is provided:

namespace MyNamespace{     [ServiceContract]     interface IMyContract     {....}     class MyContract:IMyContract     {....}}

The following shows the configuration entry required by the configuration file:

<system.serviceModel> <services> <service name="MyNamespace.MyService">    <endpoint      address="http://localhost:8000/MyService"      binding="wsHttpBinding"      contract="MyNamespace.IMyContract"    /> </service> </services></system.serviceModel>

When specifying the service and contract types, the full name of the type must be used.

      • Use base address

<system.serviceModel> <services> <service name="MyNamespace.MyService"> 


If the host does not provide a matched base address, an exception is thrown during service loading. When configuring the endpoint address, you can add a relative URI to the base address.

      • BIND configuration

You can use the configuration file to set the binding used by the endpoint. Therefore, you must add the bindingConfguration attribute in the endpoint section. The following describes how to enable transaction propagation:

 <system.serviceModel> <services> <service name="MyNamespace.MyService"> <endpoint address="net.tcp://localhost:8000/MyService" bindingConfiguration="TransactionalTCP" binding="wsHttpBinding" contract="MyNamespace.IMyContract" /> </service> </services><bindings><netTcpBinding>  <biinding name="TransactionalTCP" transactionFlow="true"/></netTcpBinding></bindings></system.serviceModel>
      • Default binding

WCF allows default binding. By default, binding affects all services of applications that use this configuration file. No name is required for default binding. As follows:

<netTcpBinding> <biinding transactionFlow="true"/></netTcpBinding>

The default binding will apply to all endpoints without explicit configuration. As follows:

 <system.serviceModel> <services> <service name="MyNamespace.MyService"> <endpoint address="net.tcp://localhost:8000/MyService" binding="wsHttpBinding" contract="MyNamespace.IMyContract" /> </service> </services><bindings><netTcpBinding> <biinding transactionFlow="true"/></netTcpBinding></bindings></system.serviceModel>

Each binding type can have a maximum of one default binding.

    • Configure endpoints programmatically

Programmatically configure endpoints by adding endpoints to ServiceHost instances through programmatic calls. ServiceHost defines multiple overloaded versions of the AddServiceEndpoint () method.

ServiceHost host = new ServiceHost(typeof (MyService));BasicHttpBinding bind = new BasicHttpBinding();host.AddServiceEndpoint(typeof (IMyervice), bind,"http://localhost:8000/MyService");host.Open();
      • Use base address
Uri httpBaseAddress = new Uri ("http: // localhost: 8000/"); ServiceHost host = new ServiceHost (typeof (MyService), httpBaseAddress); BasicHttpBinding bind = new BasicHttpBinding (); // use the base address host. addServiceEndpoint (typeof (IMyervice), bind, ""); // use the relative address host. addServiceEndpoint (typeof (IMyervice), bind, "MyService"); // ignore the base address host. addServiceEndpoint (typeof (IMyervice), bind, "http: // localhost: 8000/MyService"); host. open ();
      • BIND configuration
ServiceHost host = new ServiceHost(typeof (MyService));NetTcpBinding tcp = new NetTcpBinding();tcp.TransactionFlow = true;host.AddServiceEndpoint(typeof(IMyervice) , tcp , "net.tcp://localhost:8000/MyService");host.Open();
    • Default endpoint

If the service host does not define an endpoint and only provides a base address, WCF adds a default endpoint for the service.
WCF adds endpoints for each base address and contract, and uses the base address as the service address.
WCF will deduce the binding type based on the scheme of the base address. For HTTP, WCF uses basic binding.
Default binding will affect the default endpoint, and WCF will also name the endpoint through connection binding and contract.
You can also use the adddefaendendpoints () method of ServiceHost to explicitly add the default endpoint.

      • Protocol ing

For the default endpoint, WCF uses the base address scheme to speculate the binding type. This speculative process becomes protocol ing.
When TCP, IPC, and MSMQ are added, only one ing is selected. However, for HTTP (or HTTPS), WCF uses basic binding by default. You need to use the protoclMapping node in the configuration file to set it:

<protocolMapping>    <add binding="basicHttpsBinding" scheme="https" /></protocolMapping> 


You can also specify a special binding method:

 <protocolMapping>    <add binding="basicHttpsBinding" scheme="https" bindingConfiguration="..." /></protocolMapping>  

Protocol ing must be defined in the configuration file.

Reference: WCF Service Programming


Can a Chinese tank launch a laser-guided bomb?
Basic WCF framework tutorial

Buy the "third edition of WCF programming ".

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.