[Solution] WCF (1) Quick Start

Source: Internet
Author: User

Windows Communication Foundation (WCF) is a series of application frameworks developed by Microsoft that support data communication and can be translated into the Windows Communications development platform. integrates the mechanisms of. NET Remoting,webservice,socket of the original Windows communication and incorporates the relevant technologies of HTTP and FTP. is the best practical way to develop distributed applications on the Windows platform.

Install: WCF is already built into the. NET Framework 3.0.

Because WCF services cannot exist in isolation and need to be hosted in a running process, we refer to the process hosting the WCF service as the host. In this section, 2 service homestay services are described, and the WCF service is bound endpoint by Code and config, respectively:

    • Self-boarding (*.exe)
    • IIS Homestay (w3wp.exe)
    • Config

Self-boarding

1. Building the Project

    • Service : A console application that implements a homestay for a WCF service that references the System.servicemode assembly. (Most implementations of the WCF framework and API definitions in that assembly)
    • Client : A console application that implements the invocation side of the service, which references the System.servicemode assembly. (The generated proxy class inherits from the assembly)

2. Create a contract (contract)

WCF contains four types of contracts: service contracts, data contracts, message contracts, and error contracts. The service contract referred to here is used to declare all operations of the service.

To make an interface a contract, you need to paste the attribute label on it.

Using System.servicemodel;namespace service{    [ServiceContract] public    interface ICar    {        [ OperationContract]        string Run (int distance);}    }

  

3. Implementing the Service

Implementing the interface method can

namespace service{public    class Carservice:icar    {public        string Run (int distance)        {            return "drive" + Distance;}}}    

4. Start Boarding

WCF uses the endpoint's communication method. Endpoints include Address,binding,contract, or ABC.

Address: Specify the location of WCF

Binging: Specifies the transport protocol. (TCP HTTP MSMQ, etc.)

Contract: Specifies the behavior of the service.

Using system;using system.servicemodel;namespace service{    class program    {        static void Main (string[] args)        {            using (var host = new ServiceHost (typeof (Carservice)))            {                //Specify the endpoint for the service, specifying contract,binding,address                host. AddServiceEndpoint (typeof (ICar), New BasicHttpBinding (), "Http://localhost:10000/Car");                Host. Open ();                Console.WriteLine ("Service started successfully");                Console.read ();}}}    

(Administrator started Service.exe)

Service and Homestay success, then how do we call it. In fact, such a way cannot be called. The address that the client refers to is the metadata for the service. So we need to expose the meta-data of the service.

Using system;using system.servicemodel;using System.servicemodel.description;namespace Service{class Program {                 static void Main (string[] args) {using (var host = new ServiceHost (typeof (Carservice))) { if (host. description.behaviors.find<servicemetadatabehavior> () = null) {//service metadata allows get mode from The following URL gets the var behavior = new ServiceMetadataBehavior {HTTPGE                    Tenabled = true, Httpgeturl = new Uri ("Http://localhost:10000/Car/Metadata")}; Host.                DESCRIPTION.BEHAVIORS.ADD (behavior); }//Specify the endpoint for the service, specifying Contract,binding,address host, respectively.                AddServiceEndpoint (typeof (ICar), New BasicHttpBinding (), "Http://localhost:10000/Car"); Host.                Opened + = (o, e) + Console.WriteLine ("Service startup Success"); Host.                Open (); Console.rEAD (); }        }    }}

5. Invocation of the service

There are 2 ways to invoke a service, vs Reference service Generation proxy class, code custom proxy class (need to ensure endpoint is exactly the same).

Code Custom proxy class:

Using system;using system.servicemodel;namespace client{    class program    {        static void Main (string[] args)        {            //consistent endpoint            using (var ChannelFactory = new Channelfactory<icar> (new BasicHttpBinding (), "/HTTP/ Localhost:10000/car "))            {                //Manually create proxy class                var proxy = Channelfactory.createchannel ();                Console.WriteLine (proxy. Run (3));            }            Console.read ();}}}    

The ICAR (contract) In this case is not necessarily identical to the icar of the WCF service (referring to the namespace, the assembly name), only the method signature is consistent. (due to the contract still need the corresponding characteristics)

Using System.servicemodel;namespace client{    [ServiceContract]    interface ICar    {        [operationcontract ]        string Run (int distance);}    }

Run Client.exe on the basis of the Service.exe that the administrator runs earlier.

IIS Homestay

1. Building the Project

2. File structure

3.svc file

The Svc file is equivalent to an ASMX file, specifying a specific service through a must-command service. such as service= "Wcfservice.service1"

In VS, the browser looks at the Svc file, and the address of the SVC is the address of the service. The address of the SVC +? The WSDL is the address of the service description.

4. Invocation of the service

Similar to the self-hosted service, just change the address to the SVC.

Note that when you create a new Svc file, vs automatically modifies the Web. config file. (used to specify metadata exposure behavior for the service)

<system.serviceModel>    <behaviors>      <serviceBehaviors>        <behavior name= "" >// Specifies the default behavior          <servicemetadata httpgetenabled= "true" httpsgetenabled= "true"/>        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel>

Config

The above basic code to implement WCF, in fact, WCF is very flexible, generally use the Config method. Or Config+code (will take effect).

The configuration of WCF involves 2 types of services, the release of the service, and the invocation of the service.

Release:

<system.serviceModel>    <behaviors>      <serviceBehaviors>        <behavior name= "meta" >          <servicemetadata httpgetenabled= "true" httpgeturl= "Http://localhost:10001/Car/Metadata"/>        </ behavior>      </serviceBehaviors>    </behaviors>    <services>      <service name= " Service.carservice "behaviorconfiguration=" meta ">        <endpoint address=" Http://localhost:10001/Car " binding= "Wshttpbinding" contract= "Service.icar" ></endpoint>        <endpoint address= "http://localhost : 10001/car2 "binding=" Wshttpbinding "contract=" Service.icar "></endpoint>      </service>    </services>  </system.serviceModel>

Call:

<system.serviceModel>    <client>      <endpoint name= "car" address= "Http://localhost:10001/Car" binding= "Wshttpbinding" contract= "Client.icar" ></endpoint>    </client>  </ System.servicemodel>

When the caller is configured, the code is called in the following way. (the name in the configuration is used to distinguish between different endpoint, and the corresponding name is used in the code to create the channel stack channels)

Using system;using system.servicemodel;namespace client{    class program    {        static void Main (string[] args)        {            using (var CF = new channelfactory<icar> ("Car"))            {                Console.WriteLine (cf. CreateChannel (). Run (3));                Console.read ();}}}    

The above content outlines the WCF code and CONFIG2 methods. In real-world development, it is easier to generate proxy classes through the VS Reference service and configure WCF service tools to modify *.config. This article will not dwell on it.

Code download: Waiting to be sorted

This article never, C

This article link: http://www.cnblogs.com/neverc/p/4682394.html

[Solution] WCF (1) Quick Start

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.