WCF Simple Example

Source: Internet
Author: User
Tags msmq

WCF (Windows Communication FOUNDATION,WCF) is a software development package (software development KIT,SDK) that is based on the development and deployment of services under the Windows platform. WCF provides a runtime environment (runtime Environment) for a service that enables developers to expose CLR types as services and to use them as CLR types. In theory, creating a service does not necessarily require WCF, but in practice, using WCF can make the task of creating a service less effective. WCF is the implementation of Microsoft's definition of a range of industry standards, including service interactions, type conversions, marshaling (marshaling), and the management of various protocols. Because of this, WCF is able to provide interoperability between services. WCF also provides developers with the basic functional modules required by most applications, improving the efficiency of developers. The first version of WCF provides a number of useful features for service development, including hosting (Hosting), service instance management (Instance Management), asynchronous invocation, reliability, transaction management, offline queue invocation (disconnected Queued call) and security. At the same time, WCF provides an elegant and extensible model that enables developers to enrich its basic functionality. In fact, the implementation of WCF itself is taking advantage of such an extensible model. The remainder of this book will focus on the content and features of this many aspects. Most of the functionality of WCF is contained in a separate assembly, System.ServiceModel.dll, with a namespace of system.servicemodel.

The architecture of WCF is as follows:

The client-and server-side model for WCF is as follows:

1 Address

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

The usual format of the address is: [Base site]/[optional URI], such as "Net.tcp://localhost:8081/myservice", can read "Use the HTTP protocol to access the localhost machine, The MyService service waits for the user's call at Port 8081 "

The common format for base site is: [Transport protocol]://[machine name or domain name] [: Optional port], such as "net.tcp://localhost:8081".

WCF supports multiple transport styles:

    • HTTP is transmitted using HTTP, HTTPS protocol, and the default port number is 80.
    • TCP is transmitted using the NET.TCP protocol, with the default address of 808.
    • Peer The network (peer network) is transmitted using NET.P2P, using the Windows peering Network transmission mechanism.
    • IPC (internal process communication) is transmitted using Net.pipe, which uses Windows's named pipe mechanism to only receive calls from the same machine, and only one named pipe can be opened per machine.
    • MSMQ uses NET.MSMQ for transport, using the Windows MSMQ mechanism, you must specify the queue name, and if you are processing private queues, you must specify the queue type.

2 binding

  Bindings standardize the combination of communication patterns and interactions directly, combining these communication features reasonably. A binding encapsulates a combination of related options such as transport protocol, message encoding, reliability, security, transactional propagation, and interoperability, making them consistent.

WCF defines six commonly used bindings:

    • The basic binding is provided by the BasicHttpBinding class, exposing the WCF service as a Web service.
    • TCP bindings are provided by the NetTcpBinding class, which uses TCP protocol communication to support a variety of features, including reliability, transactional, security, and optimization of communication between WCF, with the disadvantage that the client must use WCF.
    • The IPC bindings are provided by the NetNamedPipeBinding class, which uses named pipes to transport traffic to the same machine, supporting features similar to TCP bindings, which are the best binding for performance and security.
    • Web Service bindings are provided by the Wshttpbinding class, and WS-Bindings are transmitted using HTTP or HTTPS, providing a variety of features, such as reliability, transactional, and security, that follow the WS-* standard, which is designed to support WS-* The standard system is interoperable.
    • ws bidirectional binding is provided by the Wsdualhttpbinding class and supports bidirectional communication.
    • The MSMQ binding is provided by the NetMsmqBinding class and is transmitted using MSMQ.

3 Contract

All WCF services are exposed as contracts, which are platform-independent and are a standard way of describing service functionality. WCF contains a Class 4 contract:

    • The service contract describes the service operations that the client can perform.
    • A Data contract defines the type of data that interacts with the service.
    • The error contract defines the error that the service throws, and how the service handles the error and passes the error to the client.
    • Message contract message contracts allow services to interact directly with the message, to customize the proprietary message format, and also to have their own application context, because it increases the complexity of the code, so it is not a common use.

4 End point

The endpoint is the only means by which WCF communicates,,channelfactory<t> essentially creates a service proxy for service invocation through the established endpoint. Endpoints are represented in the WCF system by the Systtm.ServiceModel.Description.ServiceEndpoint type, which contains three core attributes-address, binding, contract. An endpoint is a construct used to send and receive messages, and an endpoint is a true interface that contains all the information needed for an object interface. Each service must expose at least one business endpoint, with each endpoint having and owning only one contract. All endpoints on a service contain unique addresses, and a single service can expose multiple endpoints. These nodes can use the same or different bindings to expose the same or different contracts.

5 Meta Data

  The metadata for the service describes the characteristics of the service, which the external entity needs to understand in order to communicate with the service. The metadata for the service includes XML, the schema document (the data contract that defines the service), and the WSDL document (the method used to describe the service). When metadata is enabled, WCF automatically generates the metadata for the service 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, and the context is the core execution scope of the service instance, and the context can be empty, that is, it does not contain any service instances.

7 Hosting

  WCF service classes cannot exist in a vacuum, and 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 be hosted in more than one hosting process, which is referred to as in-process hosting if the service resides in the same process as the client. Common hosts are as follows:

    • Web site
    • Windows Forms applications
    • Windows Services
    • Windows Activation Service (WAS)

The WCF hosting architecture is as follows:

Each. NET host processes contain multiple application domains, each with 0 to more host instances, each dedicated to a particular service type. Therefore, creating a host instance is essentially registering a service host instance that contains all the endpoints for the type of host machine that corresponds to the base address. Each service host instance has 0 to more contexts. A context can be associated with 0 or one service instance.

8 Agents

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

Example

Through the above introduction, we from the contract, service, host, client these four steps to complete a simple demo, the project structure is as follows:

Define the contract, which is an interface, which is the ServiceContract tag of the interface, the exposed method is marked as OperationContract, and the data is marked as DataContract.

namespacewcfservice{//Note: Using the rename command on the Refactor menu, you can change the interface name "IService1" in code and configuration files at the same time. [ServiceContract] Public InterfaceIwcfservice {[OperationContract]stringGetData (intvalue); [OperationContract]stringGreeting (stringsName);        [OperationContract]        Compositetype getdatausingdatacontract (Compositetype composite); //TODO: Add your service actions here    }    //use the data contract described in the following example to add a composite type to a service operation. [DataContract] Public classCompositetype {BOOLBoolvalue =true; stringStringValue ="Hello"; [DataMember] Public BOOLBoolvalue {Get{returnBoolvalue;} Set{Boolvalue =value;} } [DataMember] Public stringStringValue {Get{returnStringValue;} Set{stringvalue =value;} }    }}

Implement the above interface

namespacewcfservice{//Note: Using the rename command on the Refactor menu, you can change the class name "Service1" in Code, SVC, and configuration files at the same time.      Public classWcfservice:iwcfservice { Public stringGetData (intvalue) {            return string. Format ("You entered: {0}", value); }         Publiccompositetype getdatausingdatacontract (Compositetype composite) {if(Composite = =NULL)            {                Throw NewArgumentNullException ("Composite"); }            if(composite. Boolvalue) {composite. StringValue+="Suffix"; }            returnComposite; }         Public stringGreeting (stringsName) {            return "Hello,"+SName; }    }}

The host that implements the service through bindings, that is, a+b+c

namespacewcfhost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(Wcfservice.wcfservice))) {host. AddServiceEndpoint (typeof(Wcfservice.iwcfservice),NewBasicHttpBinding (),NewUri ("Http://localhost:10000/Service/WCFService")); if(host. State! =communicationstate.opening) host.                Open (); Console.WriteLine ("Service has been started! ");            Console.ReadLine (); }        }    }}

The client needs to add a reference to the service contract.

namespacewcfclient{classProgram {Static voidMain (string[] args) {endpointaddress ea=NewEndpointAddress ("Http://localhost:10000/Service/WCFService"); Iwcfservice Proxy=ChannelFactory<iwcfservice>. CreateChannel (NewBasicHttpBinding (), EA); Console.WriteLine (proxy. Greeting ("Yulaw"));        Console.ReadLine (); }    }}

Execution results

Have you seen and Netremoting's writing a bit similar?

WCF Simple Example

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.