"The Path of Architecture: A full analysis of WCF (i)"--service contract and message mode

Source: Internet
Author: User

Microsoft announced last week that it would say. NET supports the news that is completely cross-platform and open core source code, let us feel immediately. NET to usher in its spring. Even as early as a few years ago. NET can develop Android and iOS, but this time the cross-platform put Linux into the Microsoft Strategy, later. NET developer can use VS to develop Linux applications, developer has a new choice, From Microsoft's strategic transformation can also see the Internet has entered a new model, is no longer the era of PC, mobile internet and the cloud era has arrived.

In the recent project to use WCF, the project to the data layer and program layer cut, transfer data between each other using WCF, this project is for the Bank of England Enumis do a complete set of banking system. The overall division of business into e-banking, Corporate Panel, Etam, E-commerce they constitute an online management system of the bank, in fact, such an online system is very similar to the Chinese banks, These systems work together by providing data or interfaces to each other.


The WCF full name is Windows Communication Fundation, which provides a unified, efficient development platform that can be used to build secure, reliable service-oriented applications. WCF is property-based development. It unifies a variety of distributed technologies, meaning that it provides a bridge between applications and data, between applications and applications, and by using WCF to manage interoperability between data. The unified distributed technology here says that it integrates all of the communication technologies in Windows, encapsulating them in the WCF architecture. This way, no matter what type of communication you use, you simply need to join a WCF service interface. All WCF-based applications can then communicate with each other. This enhances the flexibility between the programs.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center,
        For example, if you want to implement communication between the implementations without WCF, you may need to use different techniques. This will take a lot of time to integrate the encapsulated communication module when it is developed. It is assumed that WCF can reduce the encapsulation of modules. Use the properties of WCF to define different communication interfaces so that you can decouple between different programs or between programs and data through WCF. So that the different modules only need to focus on their own services.
        WCF encapsulates the communication services between each other and also encapsulates the security and transactional modules. Provide more secure and efficient transaction management between applications.


WCF guide map

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">
There are three basic data in the WCF configuration section. messages, services, and endpoints, respectively. The concept of service in three data includes the broadest, a WCF can be called a service, it is similar to a DLL, each service file will be generated independently of a services. Join the service reference on the party that is using the service. The information that the application sends when invoking the service is called a message, and it is a unit of data. and the messages in the computer network are similar, including the body of the message and the message header. At the end of the application, you must refer to the service you are creating by invoking the service, in fact, by adding a service endpoint to the configuration file, the reference to each service can be understood as an endpoint, and the address of the service is configured in the endpoint. Communication with each other (such as HTTP, TCP, etc.), the service's message definition.

WCF is based on attribute development, which means that services and messages can be identified by using attribute tagging for classes and methods. There are two types of service contract classes and interfaces that can be used when defining a WCF. The two service agreements have the same effect. However, it is recommended to use the interface in a way that has better extensibility and helps to keep the service contract intact, and only needs to implement the new interface again when the version number of the service is changed.



I. Service agreements


WCF creates a service by using a property to indicate that a service is indicated by using ServiceContract (service contract) above the definition of the interface or class, using OperationContract (a method contract) to indicate a message above the method definition. So it's over. A WCF definition work, assuming that the interface is required to implement the corresponding interface.

The detailed definition method looks at the following demo example, using the interface method to define the service contract.


1. Join a WCF


Joins a WCF application set. A WCF is then added to the Assembly, and when the item is joined, the WCF service is selected so that vs will add a new Svc file to implement the interface based on the self-brought template. This SVC file is the corresponding implementation class for WCF. Alternatively, you can manually write a service contract interface. and implement the corresponding method. For example, the following code:

Using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using  System.servicemodel;using system.text;namespace contracts{    //note:you can use the ' Rename ' command on the ' refactor ' menu to change the interface name "IService2" in both Code and config file together.    [ServiceContract]    Public interface IService2    {        [OperationContract]        string DoWork ();    }    public class Service2:iservice2    {public        string DoWork ()        {            return "Hello wcf!";    }}}

2. Use of the service


To use a service, there are two ways in the Assembly, one is to join the specified service by joining the service, and also to manually add the endpoint to the configuration file to implement the service.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Check the Join service reference and then pop up an interface for example to display the join of the service. You can manually enter the service address in the text box, and the same can be clicked discover let vs self-actively identify the newly added services. For example, with:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhbmdfegluegl1/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


Note: Be sure to manually generate a new service after the service is added, no error will be given when joining the service reference, showing how the service was not found.



After adding a reference to the service, the Assembly is able to use the service directly, which is like introducing a new DLL file, which only needs to introduce a namespace when used. Directly can invoke the service, here to implement a simple HelloWorld program:

Using system;using system.collections.generic;using system.linq;using system.servicemodel;using System.Text;using System.threading.tasks;using contracts;namespace consoleapplication2{    class program    {        static void Main ( String[] args)        {            IService2 service = new Service2 ();            Console.WriteLine (service. DoWork ());            Console.read ();}}}    

The execution structure is as seen in the following:




Second, the message mode


The previous section described the creation of a service for WCF and made a small demo to demonstrate the creation of WCF, which was developed using attribute annotations and is fairly straightforward to define.

Next we have a detailed discussion of the message pattern. WCF provides three message patterns, one-way mode, request/answer mode, and duplex mode, and three modes that support client-side sending of messages to the server. The difference is that one-way mode only supports message delivery and does not support return.

The request/Answer mode enables the client to send data to the server and wait for the return data at the same time, which does not support invoking the client on the server.

Duplex mode is more powerful, not only support the client to invoke the service side of the method, at the same time also support the service side call client method, powerful.

Message schema Map

1. Unidirectional modeOne-way mode, as the name implies, is a one-way request, and client loses contact with the server after the client sends a message request to the server, and the end of the request does not care if the return result continues to run down. This means that the client sends the request and continues to run down. Does not wait for the server to return a message, and the server receives the message and runs the service, such a one-way mode is actually a multi-threaded operation, the client sends the message, the client and the server will be running at the same time, so that they do not conflict with each other, is also thread-safe at the same time, Increased operational efficiency.
One-way mode only needs to add the IsOneWay attribute to the method declaration. It can indicate that the invocation of the message is using one-way mode. For example, the following code:

Using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.servicemodel.web;using system.text;namespace WcfService4{//note:you can use the "Re    Name "command on the" Refactor "menu to change the interface name" IService1 "in both Code and config file together.        [ServiceContract] public interface IService1 {//method of declaring a one-way mode message [OperationContract (IsOneWay = True)]        void GetData ();        [OperationContract]        Compositetype getdatausingdatacontract (Compositetype composite); Todo:add your service operations here}//use a data contract as illustrated in the sample below to Add Composi    TE types to service operations.        [DataContract] public class Compositetype {bool Boolvalue = true;        String stringvalue = "Hello";            [DataMember] public bool Boolvalue {get {return boolvalue;} set {boolvalue = value;}} [DataMember] public string StringValue {get {return stringvalue;}        set {stringvalue = value;}  }}}namespace wcfservice4{//note:you can use the ' Rename ' command on the ' Refactor ' menu to change the class name    "Service1" in code, SVC and config file together.  Note:in order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the    Solution Explorer and start debugging. The interface protocol that implements WCF in a service is public class Service1:iservice1 {public void GetData () {System.            Threading.Thread.Sleep (10000);            Console.WriteLine ("Hello Ha"); return string.        Format ("you entered: {0}", value);             Public Compositetype getdatausingdatacontract (Compositetype composite) {if (composite = = null)            {throw new ArgumentNullException ("composite"); } if (composite. BoolvaLue) {composite.            StringValue + = "Suffix";        } return composite; }}//called the service in the client, and the thread does not pause but continues to run the methods in the client. Namespace consoleapplication1{class Program {static void Main (string[] args) {Serviceref Erence1.            IService1 service1=new service1client (); Service1.            GetData ();            Console.WriteLine ("This Main function");        Console.read (); }    }}

The above Demo sample demonstrates the detailed process of one-way mode, and defines the IsOneWay attribute for the method when defining the interface service protocol. This causes the message to become a one-way request pattern.

After the client invokes the service's method, the thread does not stop the request, but continues to run down, in such a way that the request is a one-way mode.


2. Request/Reply mode

Such a pattern is the pattern of the WCF message pattern, which means that the client waits for the server to finish and return to the client after the server has been requested. The client will continue to run down. This approach is less flexible than one-way mode, but high security, because it is single-threaded, so security is very high, applicable to the request with data return.

Using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.servicemodel.web;using system.text;namespace WcfService4{//note:you can use the "Re    Name "command on the" Refactor "menu to change the interface name" IService1 "in both Code and config file together.        [ServiceContract] public interface IService1 {//method of declaring request/reply mode messages [OperationContract (IsOneWay = True)]    String GetData (); }}namespace wcfservice4{//note:you can use the ' Rename ' command on the ' Refactor ' menu to change the class name ' Ser '    Vice1 "in code, SVC and config file together.  Note:in order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the    Solution Explorer and start debugging. Implement WCF's interface protocol in a service public class Service1:iservice1 {public string GetData () {Syste            M.threading.thread.sleep (10000); CoNsole.            WriteLine ("Hello ha"); return string.        Format ("You apply the wcf!"); The service is called by}}//in the client, resulting in a thread that pauses based on the time of the WCF message thread and continues to run down when the pause is complete. Namespace consoleapplication1{class Program {static void Main (string[] args) {Serviceref Erence1.            IService1 service1=new service1client (); Service1.            GetData ();            Console.WriteLine ("This Main function");        Console.read (); }    }}

3. Duplex Mode

Duplex mode is relatively complex in the first two modes, it is requested in the same time for the client and the server, that is, the client can request the server side of the service side also request the client, their call relationship is mutual, that is, the client request service side of the method, At the same time, the server requests the client to exchange data in such a way that it needs to use duplex mode.
This means that the duplex mode is attached to the server and client communication mechanism at the same time. When defining duplex mode, you need to specify a callback function on the server (using the CallbackContract property) to define two interfaces at the same time. One is the service-side message interface, and the other is the interface that the client needs to implement (that is, the server-side callback method).

The server needs to implement the interface of the service, the client needs to implement the client's service contract interface.
Defines a duplex service. At the same time when defining the callback service, that is, in the client implementation of the service, that is, when declaring the service need to use CallbackContract to specify the callback contract class, in addition to define the mode of the reply, The need to use sessionmode.required means that the reply must be used. The detailed definition method is as follows:

Using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.text;namespace service{    //note:you can use the ' Rename ' command on the ' refactor ' m ENU to change the interface name "IService1" in both Code and config file together.    [ServiceContract (SessionMode = Sessionmode.required,callbackcontract = typeof (Icallback))]    Public interface IService1    {        [OperationContract]        string applydata (int value);    }    Public interface Icallback    {        [OperationContract]        string GetData (String data);}    }

It is important to pay special attention to the protocols that are required to implement services on the server and client after the service is defined. Under the duplex protocol, if the client and the server call each other, a chain-like loop is generated, The loop causes a deadlock, so it is necessary to set the concurrency mode to reentrant or multiple by using the ConcurrencyMode property of the ServiceBehaviorAttribute attribute on the party implementing the service to resolve the problem.

Using system;using system.collections.generic;using system.diagnostics.contracts;using System.Linq;using System.runtime.remoting.contexts;using system.runtime.serialization;using system.servicemodel;using System.Text; namespace service{    //note:you can use the ' Rename ' command on the ' Refactor ' menu to change the class name ' Service1 "In both Code and config file together.    [ServiceBehavior (ConcurrencyMode = concurrencymode.reentrant)]    public class Service1:iservice1    {public        string applydata (int value)        {            Icallback callBack = Operationcontext.current.getcallbackchannel<icallback> ();            String Strprint=callback.getdata ("Hahha");            return string. Format ("You applyed the data is:{0},we getted data is: {1}", strprint, Value);}}}          


Implement the client callback method:
Using system;using system.collections.generic;using system.linq;using system.servicemodel;using System.Text;using System.threading.tasks;using Consoleapplication1.servicereference1;namespace ConsoleApplication1{    class Program    {        static void Main (string[] args)        {            CallBack callback=new CallBack ();            InstanceContext instancecontext=new InstanceContext (callBack);            IService1 service1=new service1client (instanceContext);            String Strprint=service1. Applydata (+);            Console.WriteLine (strprint);            Console.read ();        }    }    public class CallBack:ServiceReference1.IService1Callback    {public        string GetData (String data)        {            return data;}}    }

Printing results:




The duplex protocol is more cumbersome to implement than the previous two implementations, so there are a lot of places to be aware of when defining it, and here are a few of the things people need to be aware of when they start learning.


NOTE1: Binding mode
When establishing a duplex contract, it is important to note that using a binding that supports duplex contracts, the default BasicHttpBinding binding does not support duplex contracts, so an error occurs when a client joins a duplex service contract. The interface defined by the protocol could not be found.

Ability to use wsdualhttpbinding bindings. The binding method is declared in the endpoint of the service. The binding methods are as follows:

<endpoint address= "" binding= "wsdualhttpbinding" contract= "Service.iservice1" >

Note2: Deadlock caused by callback
The above demo example uses the request/reply contract, which is to wait for the service to run after the service has been issued and then continue to run down the service. However, the above code did not go wrong after it was run. is due to the use of the ServiceBehaviorAttribute property at the end of the implementation of the service to specify a property, assuming that the following error occurs without specifying:


This error occurs because the service has a deadlock (deadlock) at the time of invocation, because the client invokes the server's request, and then the client is called by the server, so continuing will lead to a vicious loop, so in order to avoid this situation. The ConcurrencyMode property of the ServiceBehaviorAttribute attribute is required on the side of the service implementation to set the concurrency mode to reentrant or multiple

[ServiceBehavior (ConcurrencyMode = concurrencymode.reentrant)]public class calculatorservice:icalculator{    // Omit implementation}[servicebehavior (ConcurrencyMode = concurrencymode.multiple)]public class calculatorservice:icalculator{    Omit implementation}

Conclusion

This series of articles is mainly to the high-speed introduction to learn the application of WCF, so some places to speak more detailed, do not need to be able to skip. This article focuses on some of the WCF terminology and WCF three main message patterns from the base of WCF. These three models have their own advantages and disadvantages, in use in accordance with detailed analysis of the details.



WCF full analysis of the path to the schema (i)--service contract and message pattern

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.