[Honestly learn WCF] The second article configures WCF

Source: Internet
Author: User

Original: [Honestly learn WCF] The second article configures WCF

Learn WCF Honestly

The second article configures WCF

In the previous article, we wrote a simple WCF service and hosted it in a console application. First look at the server code:

Using system;using system.collections.generic;using system.linq;using system.text;using System.ServiceModel;using        System.servicemodel.description;namespace hellowcfservice{class Program {static void Main (string[] args)            {uri baseaddress = new Uri ("Http://localhost:8000/MyService");            ServiceHost host = new ServiceHost (typeof (Hellowcfservice), baseaddress); Host.            AddServiceEndpoint (typeof (Ihellowcfservice), New Wshttpbinding (), "Hellowcfservice");            ServiceMetadataBehavior SMB = new ServiceMetadataBehavior (); Smb.            Httpgetenabled = true; Host.            DESCRIPTION.BEHAVIORS.ADD (SMB); Host.            Open ();            Console.WriteLine ("Service is ready");            Console.WriteLine ("Press any Key to Terminate ...");            Console.ReadLine (); Host.                    Close ();    }} [ServiceContract] interface Ihellowcfservice {[OperationContract] string hellowcf (); } PubLic class Hellowcfservice:ihellowcfservice {public string hellowcf () {return "Hello wcf!"        ; }    }}


All of this code is written in Program.cs, clean and refreshing.

Let's take a closer look at this program and find that we use a lot of code to customize the features of the service, such as the base address, endpoint, bindings, behavior, and so on. These are called configurations. and the real definition of the service itself is very few (the main logic is to return a string only), so it is not difficult to see that WCF's programming in the configuration accounted for a large proportion.

The configuration options for WCF are many, and we only consider the simplest case here. After we define and implement a service contract, at least what configuration should we do to make the service run?

(1) Configure a service (ServiceHost) based on the service implementation class.

(2) Specify a base site (this step can be omitted if an absolute address is specified in the endpoint).

(3) Establish an endpoint and assign it an address, binding, and service contract.

(4) Establish a metadata exchange endpoint.

(5) Add a behavior for the service to enable metadata exchange.

Although Microsoft provides a simplified configuration under. Net 4.0, we can even do a single line of configuration, but for the sake of figuring out the fundamentals of the configuration, we will not consider simplifying the configuration for the time being.

The following configuration is what we have to do, and we can see several configuration statements from the code:

Establish Base Address:

            Uri baseaddress = new Uri ("Http://localhost:8000/MyService");


Service creation:

            ServiceHost host = new ServiceHost (typeof (Hellowcfservice), baseaddress);


Establish endpoints and specify addresses, bindings, and service contracts:

            Host. AddServiceEndpoint (typeof (Ihellowcfservice), New Wshttpbinding (), "Hellowcfservice");


Add a metadata Exchange endpoint and add enable metadata interchange behavior

            ServiceMetadataBehavior SMB = new ServiceMetadataBehavior ();            Smb. Httpgetenabled = true;            Host. DESCRIPTION.BEHAVIORS.ADD (SMB);


It seems clear, but just looks beautiful, such a configuration is a disadvantage, such as the base address, if the server after the deployment of services, the site changes, we must modify the source program and recompile to achieve this requirement. This is also true for the other configuration options. This is unacceptable for the product environment. Fortunately, WCF provides a solution for this problem: configuration files.

We write the configuration of the service in the application's configuration file (the IIS program is the Web. config other program is app. config) and we don't have to recompile the assembly when the configuration changes.

The configuration file is very complex, there are many options, in order to be easy to get started, we start with the options related to this example.

In the configuration file, the root section is <configuration>, where all the configuration elements are located. For the configuration section of the WCF service, the outermost section is <system.servicemodel>, so the configuration file should look like this at least:

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


Now we are ready to start configuring a service with a service configuration element labeled <services></services>, which is a subsection of <system.serviceModel> that can host many services on one host. Each service is configured with <service></service>, which is a subsection of <services>. Before configuring <service>, we also need to add a base address configuration, base address with <baseaddress> description, he is

Are you dizzy? Take it easy.

Add the <services> section first, here can accommodate a lot of services, note this is with S

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


In the arms of <services>, we add a <service>, this is the service ontology that we want to configure, note that this is not with s

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


In <service>, add a base address, first add a

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <system.serviceModel>    < services>      <service>        

Here, the base site part has been completed, corresponding to the location in the code you found it?

Service configuration is also very close, we specify the implementation type in the code for the service, how to specify in the configuration file? Use the Name property of the <service> tag, specifying the time to use the fully qualified name (with namespace)

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <system.serviceModel>    < services>      <service name= "Hellowcfservice.hellowcfservice" >        

My example is not good, the namespace and implementation type is a name, be aware of the distinction.

Here, the service is also configured, the corresponding code location turned up to look for a bit.

Next, the endpoint is configured with the <endpoint> element, which, as in the code implementation, requires one by one of the specified address, binding, and service contract interfaces to be represented in the configuration, respectively, with the addresses, bindings, and contract attributes, of course < Endpoint> is also a sub-section of <service>, after all, he belongs to the service.

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <system.serviceModel>    < services>      <service name= "Hellowcfservice.hellowcfservice" >        

Here with the relative address "hellowcfservice", he will be combined with the base site (in the back) to become the address of the endpoint, here can also be specified as an empty string "", the base address (that is, the service address) is the endpoint addresses, you can also specify an absolute address, so that he will overwrite the base address, The base site will not work for this endpoint, as you can see, the endpoint's address is independent, it can be a sub-address of the base site, or can be used independently of another address, there is no necessary link between them.

The contract here is the same as in <service>, also use the fully qualified name (with the namespace).

Note that when using IIS hosting, a relative address must be used, that is, the endpoint must be a child address of the base site, which is determined by the deployment structure of IIS.

Here the endpoint is also configured to complete, the location of the corresponding code to find it?

Next is the last step (or two steps) to configure the metadata exchange endpoint and turn on the metadata exchange behavior. This process, the code used three lines, in fact, the code three lines just added metadata exchange behavior, and did not configure the metadata Exchange endpoint, the runtime system for us to automatically add an endpoint. These two points are indispensable, although the system will add to us, we still need to know the wording of this configuration. This is important.

Open metadata Exchange from the principle should be two things, the first is the service allows metadata exchange, the second is the service provides metadata Exchange Mode, the first is to add metadata exchange behavior, the service allows such a request, the second is the service tells you how to request, the client is through a fixed endpoint to request, The address, bindings, and contracts of this endpoint are fixed, we cannot change, this is the framework of the Convention, we can only be configured as required.

First, the first one, which allows metadata exchange, is implemented by adding a behavior to the service, which describes the characteristics of the service, which may have the same behavior, the behavior is not unique to a service, and therefore the behavior is defined as <system.serviceModel> section of the Sub-section, can be referenced by different services, his definition of some like services, the outside is with s, inside is not with S, after all, there may be a lot of behavioral definitions.

Define a behavior first:

<?xml version= "1.0" encoding= "Utf-8"?><configuration> < system.servicemodel> <services> <service name= "Hellowcfservice.hellowcfservice" > 

Because of the service behavior and endpoint behavior, there is a <servicebehaviors> between <behaviors> and <behavior>, indicating that this is a service behavior, we have a name for the behavior, so that <service> can be referenced, or not specified, then all services will be applied. The behavior of exchanging metadata has a fixed label description, which is <servicemetadata> look at the code, it's familiar.

After establishing the behavior, to let the service we have just established refer to him, with the behaviorconfiguration attribute of <service>:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <system.serviceModel>    < services>      <service name= "Hellowcfservice.hellowcfservice" behaviorconfiguration= "MetaExchange" >        

The next step is to set up a metadata exchange endpoint with the same location as the endpoint we just created, but the property is fixed and the case cannot be written incorrectly.

<?xml version= "1.0" encoding= "Utf-8"?><configuration> < system.servicemodel> <services> <service name= "Hellowcfservice.hellowcfservice" behaviorconfiguration= "Metaexchange" > 


Here, the configuration file is finished. Let's put it in the program, open the service-side program established in the previous article, add a configuration file for the program

Right-click on the application configuration file, add new item, Project----Name system will be good (app. config). Write the above configuration in and save it.

Now that we have the configuration file, we don't have to (and should not) configure it in the code. The configuration in the code overrides the configuration in the configuration file. So we're going to change the code a bit.

There are only a few lines left in the main function:

            ServiceHost host = new ServiceHost (typeof (Hellowcfservice));            Host. Open ();            Console.WriteLine ("Service is ready");            Console.WriteLine ("Press any Key to Terminate ...");            Console.ReadLine ();            Host. Close ();

Among them, the establishment sevicehost that row was modified, removed the baseaddress parameters, but we still need to tell host the type of service class we want to register.

F5 run up.

And then try to access the service in the browser.

Http://localhost:8000/MyService


Is it the same as the result of yesterday?

(The csdn of the map seemed to hang ...)

Summarize today's study.

We have used the configuration file method to complete the configuration of the WCF service, which is exposed to the configuration methods of the service, endpoint, and behavior. There are many elements of the configuration file, such as bindings, security, and so on. In the future to learn the time to expand slowly, each element of the configuration file should strive to write down, a line of writing, in the process of writing experience, rather than copying and pasting around, so that the configuration file can be written in a deep impression.

Related Resources

Xu Changlong teacher spoken "with me from the beginning to learn the WCF series course"

http://msdn.microsoft.com/zh-cn/hh148206

WCF reference in the MSDN technology repository

Http://msdn.microsoft.com/zh-cn/library/dd456779.aspx

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Honestly learn WCF] The second article configures WCF

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.