MSDN Library
Inhaltsverzeichnis reduzieren
Inhaltsverzeichnis erweitern
EN
Dieser Inhalt ist in Ihrer Sprache leider nicht verfügbar. Im Folgenden finden Sie die englische Version.

Understanding Windows Communication Foundation

This article provides an introduction to Windows Communication Foundation (WCF) followed by a list of what's new for WCF in .NET Framework 3.5. In the companion topic, Developing Connected Systems, the concepts discussed here are illustrated with code from the DinnerNow.net sample application. The Windows Vista Developer Story article Windows Communication Foundation contains additional background information.

Windows Communication Foundation, a core component of .NET Framework 3.0, provides a service-oriented programming model, run-time engine, and tools for building connected applications. WCF unifies and extends the functionality of existing Microsoft connecting technologies by providing a single programming model independent of underlying communications protocols. WCF applications use open standards and protocols to interoperate with existing Microsoft and non-Microsoft technologies.

WCF models network communication that consists of message exchanges between a client and a service. When a client sends a message, it travels through multiple layers of software, each performing some operation on the message, before being transported across the network to the server. At the server, the message again travels through multiple layers of software before being delivered to the service. These multiple layers of software are known as the communication stack. Each layer is governed by one or more standards or protocols, which specify the end result of the operation on the message at that layer.

In WCF, the communication stack is represented as a binding. A binding consists of a set of binding elements, each of which represents a layer in the stack. The implementation of a binding element is known as a channel. At run time, WCF assembles the stack of channels specified by the binding. When data is sent, WCF translates the data into a message and passes the message through the stack of channels, so that the message is sent in accordance with the protocols identified by the binding. This process is reversed on the receiving end.

The core concept behind WCF is the service, which is a .NET type that implements one or more service contracts with each contract exposed through an endpoint.

An endpoint expresses all the information needed by a client to communicate with a service. An endpoint consists of an address, a binding, a contract, and optional behaviors.

The address specifies where the service is located for a specific service contract. The binding declares the set of protocols that are used to send and receive messages. The contract defines the kind of messages that can be sent and received. Behaviors control optional service and client functionality.

Endpoints can be defined programmatically or in an XML configuration file. WCF provides the Service Configuration Editor (SvcConfigEditor.exe) tool to aid in the creation and modification of endpoint XML definitions as well as other settings. The following portion of an XML configuration file shows an example of two endpoint definitions, which are discussed in subsequent sections.

<service name="ProcessOrder">
  <host>
    <baseAddresses>
      <add baseAddress="http://localhost:10021/dinnernow" />
    </baseAddresses>
  </host>
  <endpoint 
    address="orderProcess" 
    binding="wsHttpContextBinding"
    contract="IProcessOrder" />
  <endpoint
    address="mex"
    binding="mexHttpBinding"
    contract="IMetadataExchange" />
</service>

For more information, see Windows Communication Foundation Endpoints.

Cc179585.collapse_all(en-us,MSDN.10).gifAddress

The address of an endpoint is represented by the EndpointAddress class, which contains a Uri property used to locate the endpoint, an Identity property used for authentication of the endpoint, and an optional Headers collection property used for customization. In the XML representation, the Uri property is specified by the address attribute of the endpoint element and the Identity and Headers properties are specified as child elements.

An address can be specified as absolute or as relative to a base address for the service. A base address simplifies the specification of multiple endpoints for a service and also allows for metadata discovery of the endpoint information. The scheme of the address ('http' in the preceding example) must match the transport of the corresponding binding.

In the preceding XML example, http://localhost:10021/dinnernow/orderProcess is the address of the endpoint corresponding to the IProcessOrder contract implemented by the ProcessOrder service.

When a WCF service is hosted in Internet Information Services (IIS) or Windows Process Activation Service (WAS), the address of the service is determined by the location of the corresponding service (.svc) file in the virtual Web directory; the address in the configure file is left empty.

For more information, see Specifying an Endpoint Address.

Cc179585.collapse_all(en-us,MSDN.10).gifBinding

A binding consists of an ordered stack of binding elements, or channels, each of which specifies part of the communication stack for the endpoint. WCF includes a set of system-provided bindings, such as the BasicHttpBinding and NetTcpBinding bindings, which are designed to cover most application requirements.

For custom bindings, the two lowest layers in the stack must be specified: the transport binding element at the base of the stack and, just above it, the element that specifies the message encoding. Binding elements that specify the remainder of the stack are optional.

For more information, see Windows Communication Foundation Bindings.

Cc179585.collapse_all(en-us,MSDN.10).gifContract

A service contract specifies the set of operations (methods) that can be called on an endpoint. A service contract is defined by applying the ServiceContractAttribute attribute to an interface or class declaration, and applying the OperationContractAttribute attribute to each method that is included as an operation of the service. Methods not marked with OperationContractAttribute are not exposed for use by clients of the service.

The IsOneWay property of the RestaurantOrderComplete operation indicates that the operation does not return a reply message. If the IsOneWay property is false or missing, the operation sends a reply message even for a method with a void return value.

The data type of each parameter or return value that participates in the contract must have the DataContractAttribute attribute applied. This attribute allows the type to be exchanged (serialized and deserialized) with the service.

All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, are serializable and considered to have an implicit data contract. Many .NET Framework collection and enumeration types also have implicit data contracts. For a list of these types, see Types Supported by the Data Contract Serializer.

Custom types used in the data exchange that contain any member types that don't have an implicit data contract, must apply the DataMemberAttribute attribute to these members to allow them to participate in the exchange.

For more information, see Designing Service Contracts, Designing and Implementing Services, and Using Data Contracts. The following code shows an example of a service contract and a data contract.

[ServiceContract]
interface IProcessOrder
{
    [OperationContract(IsInitiating = true)]
    void Processorder(DinnerNow.Business.Data.Order newOrder);

    [OperationContract(IsOneWay = true)]
    void RestaurantOrderComplete();
}

namespace DinnerNow.Business.Data
{
    [DataContract]
    [Serializable]
    public class Order 
    {
        [DataMember]
        public OrderItem[] OrderItems { get; set; }
    }
}

Cc179585.collapse_all(en-us,MSDN.10).gifBehaviors

Behaviors are types that modify or extend service or client functionality. There are four kinds of behaviors in WCF:

  • Service behaviors (IServiceBehavior types) enable the customization of the service runtime including ServiceHostBase. For example, the ServiceMetadataBehavior class (<serviceMetadata>) controls the publication of service metadata and associated information.

  • Endpoint behaviors (IEndpointBehavior types) enable the customization of service endpoints. For example, the WebHttpBehavior class (<webHttp>), when used in conjunction with the WebHttpBinding binding, enables WCF to expose and consume Web-style services.

  • Contract behaviors (IContractBehavior types) enable the customization of the ClientRuntime and DispatchRuntime classes on the client and service, respectively.

  • Operation behaviors (IOperationBehavior types) enable the customization of the ClientOperation and DispatchOperation classes on the client and service, respectively.

For more information, see Specifying Service Run-Time Behavior.

Metadata allows a client, knowing only a service's base address, to retrieve the service's endpoint information, which is everything that the client needs for further communication with the service.

Metadata describes the addresses, bindings, and contracts, but not behaviors, of the service and, by default, is in the form of the Web Services Description Language (WSDL) and WS-MetadataExchange (WS-MEX) standards. Clients query for metadata using a GET request.

Metadata is not published by default; a service must enable the ServiceMetadataBehavior behavior and provide a metadata endpoint. For an example of a metadata endpoint, see the second endpoint (with the "mex" address) in the example under the Endpoints heading. The following portion of an XML configuration file shows the enabling of the ServiceMetadataBehavior behavior. For more information, see Publishing Metadata Endpoints.

<serviceBehaviors>
  <behavior name="WorkflowServiceBehavior">
    <serviceMetadata httpGetEnabled="true" />
  </behavior>
</serviceBehaviors>

A service must be hosted within a run-time environment that creates the service and controls its context and lifetime. WCF services are designed to run in any Windows process that supports .NET Framework 3.0. Hosting options range from a simple console or Windows form application to a Windows service, IIS, and Windows Process Activation Service (WAS). For more information on hosting options, see Hosting Services.

Cc179585.collapse_all(en-us,MSDN.10).gifWindows Application

WCF services can be hosted in any managed application. This option requires the least infrastructure to deploy; an instance of ServiceHost is simply created and opened to make the service available. This option is convenient for testing the service during development. The following example shows a service hosted by a console application.

static void Main(string[] args)
{
    private static ServiceHost restaurantOrderServiceHost = 
         new ServiceHost(typeof(RestaurantOrderService));
         
    restaurantOrderServiceHost.Open();
    // ...
    restaurantOrderServiceHost.Close();
}

Cc179585.collapse_all(en-us,MSDN.10).gifWindows Service

WCF services can be hosted in a Windows service where their lifetimes are controlled by the Windows Service Control Manager (SCM). The hosting code is similar to that above for the console application except the ServiceHost.Open and Close methods are called from overridden ServiceBase.OnStart and OnClose methods, respectively. Additionally, installation components must be created that install and register the Windows service.

Cc179585.collapse_all(en-us,MSDN.10).gifIIS

WCF services that communicate only over the HTTP protocol can be hosted in IIS, where they can take advantage of IIS features such as process recycling, idle shutdown, process health monitoring, rapid fail protection, and the common configuration system. IIS must be properly configured, but the writing of hosting code as part of the application is not required.

Cc179585.collapse_all(en-us,MSDN.10).gifWAS

WCF services that communicate over certain non-HTTP protocols, such as TCP, MSMQ, and Named Pipes, can be hosted in the new Windows Process Activation Service. WAS uses the IIS 6.0 process model and hosting features, but removes the dependency on HTTP. IIS 7.0 uses WAS for message-based activation over HTTP. Message-based activation over other WCF protocols is enabled by WCF components that plug into WAS. Applications that use these communication protocols can now take advantage of the IIS features that were previously only available to HTTP-based applications.

To host a service, a new application is created in WAS (using the IIS Manager tool or Visual Studio®). The virtual directory must contain the following:

  • The service implementation (either compiled in the /bin folder or as source code in the /App_Code folder).

  • A service file (.svc).

    The service file provides the connection between a URI (the address of the service) and the service implementation. The @ServiceHost directive specifies the service and the service host factory used to instantiate the service. If the Factory attribute is unspecified, the ServiceHostFactory class is used, which returns an instance of the ServiceHost class. The following is an example of a service file that specifies a WorkflowServiceHost.

    <% @ServiceHost
        Service="DinnerNow.OrderProcess.ProcessOrder"
        Factory="System.ServiceModel.Activation.WorkflowServiceHostFactory" %>
    
  • A Web.config file, which defines the service settings in the <system.serviceModel> section.

For more information, see Extend Your WCF Services Beyond HTTP with WAS.

Some of the tools provided by WCF include:

  • Service Configuration Editor (SvcConfigEditor.exe)

    Uses a graphical user interface (GUI) to create and modify settings located in the <system.serviceModel> section of a WCF configuration file. This section contains client, services, bindings, behaviors, and diagnostics settings. A wizard is provided that steps through the configuration of a WCF service or client

  • Service Trace Viewer Tool (SvcTraceViewer.exe)

    Allows trace messages to be viewed, grouped, and filtered.

  • ServiceModel Metadata Utility (Svcutil.exe)

    Generates code for service contracts, clients, and data types from metadata; creates metadata from compiled assemblies or running services.

  • ServiceModel Registration Tool (ServiceModelReg.exe)

    Manages the registration of the ServiceModel assembly.

  • Workflow Service Registration Tool (WFServicesReg.exe)

    Manages the registration of WF services.

  • WCF Service Host (WcfSvcHost.exe)

    Uses the Visual Studio debugger to host a service. The service can then be tested using the WCF Test Client tool or some other client.

  • WCF Test Client (WcfTestClient.exe)

    Submits input parameters to a service and shows the response that the service sends back. This GUI tool provides a seamless service testing experience when combined with the WCF Service Host tool.

  • WCF Visual Studio Templates

For more information, see Windows Communication Foundation Tools and Using the WCF Development Tools.

WCF is enhanced with the following new and changed features in .NET Framework 3.5. For more information, see the WCF section in What's New in the .NET Framework Version 3.5.

  • Workflow services

    Integrates Windows Workflow Foundation (WF) and WCF, allowing WCF services to be implemented and authored using WF workflows and workflows to be exposed as services.

  • Durable services

    WCF services that use the WF persistence model to persist state information.

  • WCF Web programming model

    Enables Web-style services with WCF. For more information, see Web Programming Model.

  • WCF and ASP.NET AJAX integration

    WCF Web services that are accessible using Asynchronous JavaScript and XML (AJAX). For more information, see AJAX Integration and JSON Support.

  • WCF syndication

  • WCF partial trust changes

Community-Beiträge

HINZUFÜGEN
Anzeigen:
© 2016 Microsoft