Luohe first recognized WCF5 and wcf5

Source: Internet
Author: User

Luohe first recognized WCF5 and wcf5

Then we add an endpoint in <Client>, which is the end point of the Client. We mentioned earlier that communication actually occurs between two endpoints, the client also has an endpoint. However, requests are always initiated from the client first, so the endpoint address should be filled in as the endpoint address of the server for the client to address, however, the service agreement must be available locally on the client. Therefore, the fully qualified name of the protocol defined locally must be written:

 

Reference http://blog.csdn.net/songyefei/article/details/7389186

Article 5 exploring communication-ClientBase

 

In the previous article, we put aside service references and metadata exchange, manually added metadata code to the client, and used the channel factory ChannelFactory <> class to create a channel, implements communication with the server. However, there are more than one programming model for communication with the server. Today we will learn to use another service class ClientBase <> to do the same job and understand how to use this class, we can understand the key part of service reference.

 

 

 

The ClientBase <> class is also a generic class that accepts service agreements as generic parameters. Unlike ChannelFactory <>, this class is a base class, that is, an abstract class, it cannot be used directly as an object. We need to write a class to inherit this class. The newly written class is instantiated as a client proxy, this object can call some protected methods of the base class to implement communication. ClientBase <> well encapsulated for us. We only need to write a new class to inherit it. He has done a lot of communication for us, for example, you don't need to create a channel or open a channel. You just need to call the Protocol method directly. This is also why service references and other metadata generation tools (such as svcutil) use this class to construct client proxies.

 

 

 

We learn from each other

 

 

 

1. Create a client program

 

We still don't need service references, but we are writing them all by hand. This time we will create a console application as the client.

 

2. Add necessary references

 

The ClientBase <> class we use is in the System. ServiceModel assembly. Therefore, we need to add a reference to this Assembly and add the using statement to program. cs.

    1. Using System. ServiceModel;

This step should be very familiar. If you have any questions, return to the previous articles for further study.

Because the service reference is not used, the client does not have any metadata, so we need to hand-write it. First, write the service agreement. I am not familiar with this yet (written after the Program class ):

    [ServiceContract]      public interface IHelloWCF      {          [OperationContract]          string HelloWCF();      }  

4. Compile the client proxy class

As mentioned above, we need to write a new class to inherit the ClientBase <> base class. In this way, this new class is the proxy class. At the same time, in order to use the proxy class to directly call the service agreement method, we also need to let the proxy class implement the service agreement interface. Note that inheritance should be written first, and the Implementation interface should be written later. We name this class HelloWCFClient.

    public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF      {             }  

ClientBase <> there are many constructors that use different types of parameters to create proxy objects. In fact, these parameters are metadata information, just now, we have passed the generic parameter to the metadata of the base class service agreement. Now, the base class still needs to bind the metadata with the endpoint address to create a correct connection, therefore, the new class we inherit should overwrite the constructor to accept the two metadata parameters and pass them to the base class.

public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF  {      public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)          : base(binding, remoteAddress)      {             }  } 

We can see that the newly created constructor does nothing, but accepts two parameters, one is binding, the other is the endpoint address, and then directly calls the base class (that is, ClientBase <>) the constructor passed the two parameters. In fact, the work is done by ClientBase <>. The class we create is a message. Otherwise, how can we call it a proxy? He doesn't do anything.

Since we have implemented the service agreement interface, of course we need to implement the interface method. Below we will write down the implementation of the method:

public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF  {      public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)          : base(binding, remoteAddress)      {             }        public string HelloWCF()      {          return base.Channel.HelloWCF();      }  } 

Don't forget your situation, mortal! We are on the client. How can we have a service agreement? This can be done, but this implementation is not implemented. Instead, we need to communicate with the server for the server to do it. Here we can see the distinctive characteristics of the proxy. Although the proxy class implements the service agreement method, however, in the method, he calls the channel on the base class (that is, ClientBase <>) and calls the Protocol method through the channel. At this time, ClientBase <> has already established a channel with the server, and is built using a service agreement. Of course, we can call the service agreement method on the channel. Therefore, the HelloWCF () process of calling the proxy object is that the proxy delegate base class calls the Protocol method on the established service protocol channel and obtains the return value from the server, then return it to the caller of the proxy class object. Dog leg, dog leg.

5. Compile the program subject

The proxy class has been written. Now we are writing the Program body. Let's go to the Main function of Program.

There are still some preparations to be done, but there are still two pieces of metadata, right, that is, binding and address. As in the previous article, we first set up the two metadata objects for backup:

    WSHttpBinding binding = new WSHttpBinding();      EndpointAddress remoteAddress = new EndpointAddress("http://localhost/IISService/HelloWCFService.svc");  

Next we need to create our proxy class object. Let's get a new one:

    HelloWCFClient client = new HelloWCFClient(binding, remoteAddress);  

Pass the two metadata objects we just created as parameters.

 

Next, you can call the service agreement method:

string result = client.HelloWCF(); 


Don't forget to close the channel. ClientBase <> this method is very considerate for us, so we don't have to force type conversion or something (see the previous article ).

Client. Close ();

All the code for Program. cs is as follows:

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;    using System.ServiceModel;    namespace ConsoleClient  {      class Program      {          static void Main(string[] args)          {              WSHttpBinding binding = new WSHttpBinding();              EndpointAddress remoteAddress = new EndpointAddress("http://localhost/IISService/HelloWCFService.svc");                HelloWCFClient client = new HelloWCFClient(binding, remoteAddress);                string result = client.HelloWCF();                client.Close();                Console.WriteLine(result);              Console.ReadLine();          }      }        [ServiceContract]      public interface IHelloWCF      {          [OperationContract]          string HelloWCF();      }        public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF      {          public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)              : base(binding, remoteAddress)          {                     }            public string HelloWCF()          {              return base.Channel.HelloWCF();          }      }  } 

6. expand a little bit.

This seems to have been quite successful. Now we can open the reference. cs code referenced by the Service to see if most of them understand it? Supervision in some places he may write something complicated, such as describing the Protocol's property parameters and more constructor classes, but the core is what we just wrote, A lot of wsdl is not the core. If you don't believe it, you can delete them and leave a reference. how is cs unavailable? The pile of things is neither useless nor complicated. Now, we will learn a little bit later.

 

Let's take a closer look at the reference referenced by the Service. there is one thing in the cs code that we do not have, that is, the establishment of the endpoint address and the binding, and we did not provide the two things when using service references, simply drop the service agreement method (see article 1). Where can I find these two key metadata elements for service reference?

 

In the configuration file, the client we created does not have a configuration file. We can put both elements in the configuration file to avoid hard encoding.

 

Add an application configuration file for our console application. Right-click the project and choose add> new project> application configuration file. Keep the default name app. config.

Open it and there is no actual content in it:

    <?xml version="1.0" encoding="utf-8" ?>      <configuration>      </configuration>  

We should be familiar with the configuration service. If you forget it, go back to the second article and review it.

First, add the <System. ServiceModel> section. Either the server or the client, as long as it is a WCF Service configuration, in this section:

<?xml version="1.0" encoding="utf-8" ?>  <configuration>    <system.serviceModel>          </system.serviceModel>  </configuration> 

Here we want to configure the Client, so we will not add the <Services> section, but change it to <Client>:

    <?xml version="1.0" encoding="utf-8" ?>      <configuration>        <system.serviceModel>          <client>                      </client>        </system.serviceModel>      </configuration>  

 

If you forget the content of the IIS service we configured in article 3, it may be slightly confusing. The address here seems to be a service address rather than an endpoint address, this is because we set the endpoint address in IIS to a null string. In this case, the service address is the endpoint address. Note that the fully qualified namespace of the contract is the ConsoleClient namespace of the client program, which also indicates that the type is defined locally. Do not make a mistake.

 

Save, the configuration has been written. If you look at the configuration generated by the service reference for us, you will see a bunch of things, which are actually the core of this.

 

Since we have already declared the binding and Endpoint addresses in the configuration, it is no longer needed in the code.

First, let's modify the proxy class to provide him with a constructor without parameters. Otherwise, when he is new, he will ask for two parameters.

public HelloWCFClient()      : base()  {     } 

Or do nothing, directly call the base class's no-argument constructor.

 

Modify the Main function, remove the declaration of the endpoint object and address object, and use the non-argument constructor to create an instance of the new proxy class:

    static void Main(string[] args)      {          HelloWCFClient client = new HelloWCFClient();                string result = client.HelloWCF();                client.Close();                Console.WriteLine(result);          Console.ReadLine();      }  

Run F5. The result is as follows!

This is basically the same as service reference. We have written the core part of service reference.

The complete code of the modified Program. cs is as follows:

    using System;      using System.Collections.Generic;      using System.Linq;      using System.Text;            using System.ServiceModel;            namespace ConsoleClient      {          class Program          {              static void Main(string[] args)              {                  HelloWCFClient client = new HelloWCFClient();                        string result = client.HelloWCF();                        client.Close();                        Console.WriteLine(result);                  Console.ReadLine();              }          }                [ServiceContract]          public interface IHelloWCF          {              [OperationContract]              string HelloWCF();          }                public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF          {              public HelloWCFClient()                  : base()              {                             }                    public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)                  : base(binding, remoteAddress)              {                             }                    public string HelloWCF()              {                  return base.Channel.HelloWCF();              }          }      }  

7. Summary

Through this study, we are familiar with another method of communicating with the server, that is, using ClientBase <> to derive the proxy class method, which is actually the method used by the Service reference, we can say that we have handwritten the implementation of a service reference at the simplest level.

 

Both ChannelFactory <> and ClientBase <> can communicate with the server. This is the highest level of communication method supported by the class library. In fact, there are more underlying channel communication methods, we will not go into depth now. The choice of the two methods depends entirely on the developers, some people like the factory, and some people like the agent class. Now that we have mastered it, choose whatever it is.

 

So far, we have a basic understanding of communication. We can only look at it as a preliminary study. However, I believe that this small depth will greatly help us in our future studies.

 

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.