Introduction to WCF in C # 1-Simple WCF Example

Source: Internet
Author: User

The first step : Create an empty solution by creating a new WCF Service Application project (using the default name) to impersonate the server, creating a new Console Application project (name changed to ConsoleApp) to impersonate the client.

The second step: Simple Analysis Wcfservice_1 project, the project content is as follows:

Bottom line: This project simulates the server side, the Service1.svc file encapsulates the service reference provided to the client, and the Service1.svc.cs file is the specific implementation of the service reference. But here because the main content of the Service1.svc.cs file--service1 class is the IService1 interface that inherits from the IService1.cs file, so the play is halved to the IService1.cs file.

First look at the IService1.cs file, from the name can be seen that this is an interface file, which defines a number of interfaces, the interface declares some methods. I'm adding two classes public class Student1, public class Student2, and a method Student1 Studentwritename (string name) as a test. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.ServiceModel.Web;usingSystem.Text;namespacewcfservice_1{//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 InterfaceIService1 {[OperationContract]stringGetData (intvalue);        [OperationContract]        Compositetype getdatausingdatacontract (Compositetype composite); //TODO: Add your service actions here // New method [OperationContract] Student1 studentwritename (stringname); }    //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;} }    }    #region new Stu Class[DataContract] Public classStudent1 {stringname; [DataMember] Public stringName {Get{returnname;} Set{name =value;} }    }     Public classStudent2 {stringName ="Zhang San";  Public stringName {Get{returnname;} Set{name =value;} }    }    #endregion}

The above code should pay attention to the following aspects:

2-1. Service Contract

Interface IService1 is preceded by [ServiceContract] , meaning that this interface (including the class that inherits this interface) is declared as a service contract, the service contract is to the client, that is, this interface exposed to the client, is to allow the client to see this interface. But see interfaces do not express can be seen in the interface declaration method, this is different (the reason is very simple, even if the interface is visible, but there are some of the methods are visible others are not visible), if you want to declare the method is visible to the client, you have to declare the method of the signature plus [ OperationContract], which is also called a service contract. Summary: There are two types of service contracts,[ServiceContract] is the declaration interface, the class is visible to the client,[OperationContract] is the specific declaration of those methods in the class is visible to the client.

2-2. Data Contract

The interface comes with class Compositetype and our custom class Student1, Student2 preceded by [DataContract] , meaning that this class is declared as a data contract, so the client can use this class to define the variable. The class mentioned here is slightly different from the one mentioned above, and the class above is biased towards methods that can be called in a class, where the class is biased to refer to as a type (like an int string), which can be used to define a variable. The class is visible to the client, but the fields and variables in the class are not necessarily (as the theory says), and are preceded by [DataMember] in the fields and variables that you want to expose to the client . However, you cannot precede a method (such as a constructor) with [DataMember]because the function can only be declared as a service contract (plus [OperationContract]), and the service contract can only be in [ ServiceContract] is declared below. Summary: There are two types of data contracts,[DataContract] is a declaration of a class or struct,[DataMember] is a specific field or property in a declaring class or struct (the recommended property) is visible to the customer.

look again at the Service.svc.cs file. you can see that it just defines a class Service1 that inherits the IService1 interface, and the main content is to implement the method declared in the IService1 interface. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.ServiceModel.Web;usingSystem.Text;namespacewcfservice_1{//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. //Note: In order to start the WCF test client to test this service, select Service1.svc or Service1.svc.cs in Solution Explorer and start debugging.      Public classService1:iservice1 { 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; }        #region New Method                 PublicStudent1 Studentwritename (stringname) {Student1 S1=NewStudent1 (); S1. Name=name; returnS1; }        #endregion    }}

There is no [ServiceContract] or [OperationContract] declaration in front of the defined class or the implementation method, because the class inherits the interface already declared, so the class does not have to declare [ ServiceContract] , the method of implementing the interface does not need to add [OperationContract] .

Maybe you have a problem with adding your own method in this class, okay? The answer is yes, but it doesn't make sense. Because in this class as the server (it can be said that), the inside of the method is to use for the client, then the declaration of the method before adding [OperationContract], but only added [ServiceContract] The method in the class of the property can be that way, and because the class inherits an interface with the [ServiceContract] attribute, the class does not have to add the [ServiceContract] property (already). In a word, it is not necessary to inherit the class that implements the interface of the service contract. Add your own method. Add it to the interface first.

Of course, if you do not use the interface (can not interface, with the interface just for more object-oriented only), directly in the class to define the service contract, directly to the interface of those [ServiceContract], [OperationContract] Just copy it over.

Step three: Analyze the ConsoleApp project

Bottom line: That thing in the red box is called a service reference, which is the client, which is the way to invoke the methods and custom types provided by the server. Add the following method:

Right-click on the ConsoleApp project and select Add Service reference (using default name), a box will pop up:

The "discovery" on the right will retrieve the found service and display it on the left, and show the address as well. Point left service found in the service left Triangle, one level open, impressively found inside is Service1 class, and then down is the Service1 class inherited interface IService1! Corresponding to the right is the method that the service provides to the client!

Open the Program.cs file in the ConsoleApp, the code is very simple, define a student1 class of variables, and then get one of her property values and output.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapp_1{classProgram {Static voidMain (string[] args) {            //defines the communication pipeline client, which is used to invoke the methods provided by the serverServicereference1.service1client client =Newservicereference1.service1client (); stringstr = client. GetData (1);            Console.WriteLine (str); //classes provided to clients by the serverServicereference1.student1 STU1 =Newservicereference1.student1 (); STU1= client. Studentwritename ("Zhang San"); Console.WriteLine ("My Name:"+STU1.            Name);                    Console.readkey (); }    }}

ServiceReference1 (actually a namespace) is the name of the service reference you just added. When you enter ServiceReference1., you'll see the type, interface, and so on that the IntelliSense namespace can refer to ( sometimes not appearing as you would like, right-click WcfService1 Project selection to regenerate, Then right-click on the ConsoleApp project's SERVICEREFERENCE1 Select Update Service Reference, this is easy to forget, each to the server to do any changes to do so . The figure is as follows:

It also defines what a communication pipeline is, which is estimated to encapsulate the method of the client-side reference provided by the server into a class that can be invoked by this class, as shown in the code.

Finally press F5 to run, no problem, right? No output? This is normal, if you want to see the output, you can first assign a value to the Str attribute (stu.str = "123";). Hey, that's even done.

Reprint: http://www.cnblogs.com/zouzf/archive/2012/02/28/2370667.html

Finally, there are two more questions:

1, in the IService1 interface to customize the two classes Student1 and Student2, why input ServiceReference1. After the IntelliSense only student1 type and no student2 type? Because there is a method public Student1 studentwritename (string name) in the IService1 interface, the return value of this method is the Studnet1 type, which is the difference .... Is that you want to use a custom type on the service side of the client, in addition to the [DataContract] declaration, there is a service contract (method) that returns a value of this type. As for why, I do not know. Ask for answers

2. The str attribute in the Student1 class has a get{return str;} method, and the field STR has a default value, why is a variable of the Student1 class defined in Program.cs, the value of the STR attribute is obtained and the output is blank? That is, the default value of the property has been lost! Why? Don't know, ask the answer ...

Introduction to WCF in C # 1-Simple WCF Example

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.