Sie sind auf Seite 1von 43

Module 2:

Getting Started with


Microsoft Windows
Communication
Foundation Development
Module Overview
Service Contract and Implementation

Hosting WCF Services

WCF Behaviors

Consuming WCF Services


Lesson 1: Service Contract and Implementation
Service Development Life Cycle

WCF Service Contracts and Data Contracts

Defining Service Contracts and Data Contracts

Service Implementation Considerations

Implementing a WCF Service


Service Development Life Cycle

Contract: Decide what data and operations will be


exposed

Implementation: Create a CLR class that implements


the contract

Hosting: Create endpoints and listen for requests

Testing: Make sure the service behaves correctly

Consumption: Create a client


WCF Service Contracts and Data Contracts

The first issue for any distributed system is considering


what to expose

Service Contract: Operations


Data Contract: Data representation

Service contracts expressed as C# interfaces

Data contracts expressed as C# classes

Attributes are used to convert C# entities into WCF


declarations
Defining Service Contracts and Data Contracts

[ServiceContract]
public interface IComplexCalc
{
[OperationContract]
int Add(int a, int b);

[OperationContract]
ComplexNumber ComplexAdd(ComplexNumber a,
ComplexNumber b);
}

[DataContract]
public class ComplexNumber
{
[DataMember]
public int Real { get; set; }
[DataMember]
public int Imaginary { get; set; }
}
Service Implementation Considerations

A WCF service is an implementation of the service


contract interface

Place the contract and implementation in


different assemblies

The implementation has to consider the WCF instancing


and concurrency model
Implementing a WCF Service

The ComplexCalc service implements the IComplexCalc


service contract

public class ComplexCalc : IComplexCalc {


public int Add(int a, int b) {
return a + b;
}
public ComplexNumber ComplexAdd(ComplexNumber a,
ComplexNumber b)
{
return new ComplexNumber()
{
Real = a.Real + b.Real,
Imaginary = a.Imaginary + b.Imaginary
};
}
}
Lesson 2: Hosting WCF Services

Responsibilities of a WCF Binding Elements Are


Host Channels
Client-Server Predefined Bindings and
Communication Via Custom Bindings
Messages
Commonly Used Bindings
Messages Are Exchanged
Between Endpoints Configuring Binding in the
Configuration File
Address, Binding, Contract
Configuring Binding in Code
Responsibilities of a Binding
Creating a Custom Binding
Message Pipeline
Defining an Endpoint
Binding Elements
Creating a Service Host

Opening a Service Host


Responsibilities of a WCF Host

A host brings the service into life

Attach the WCF infrastructure to the service

Create endpoints and listen for requests

An endpoint is a combination of
Address
Binding
Contract
Client-Server Communication Via Messages

Client Message Service

Message
Messages Are Exchanged Between Endpoints

Client Service

Endpoint

Endpoint Message Endpoint


Address, Binding, Contract

Client Service
A B C

C B A Message A B C

Address Binding Contract


(Where) (How) (What)
Responsibilities of a Binding

Encapsulates all the technology concerned with


communication and messages handling

Defines the transport technology (for example HTTP,


TCP)

Defines the message encoding

Defines protocols and standards (for example security)

Defines messaging properties (for example timeouts)


Message Pipeline

Client Service

Reliable Reliable
Messaging Messaging

B B
I Security Security I
N N
D D
I I
N Encoding Encoding N
G G

Transport Transport
Binding Elements
Binding Element

Binding
HTTP Text Security Reliability Transactions

Transport Encoders Protocol


TCP HTTP Text Security Reliability

MSMQ IPC Binary Transactions .NET

Custom
Custom Custom
Binding Elements Are Channels

Each binding element defines a channel

Each channel has an inner channel; messages flow


between the innermost channels

Security Security

Encoding Encoding

TX TX
Transport
Predefined Bindings and Custom Bindings

There are many predefined bindings designed for


common scenarios

Predefined bindings are easier to use

You define a custom binding with a custom combination


of binding elements

Usually there is no need to define a custom binding


Commonly Used Bindings

Binding Summary

basicHttpBinding HTTP transport, text encoding

wsHttpBinding HTTP transport with WS-* support

netTcpBinding TCP transport, binary encoding,


WS-* support
netMsmqBinding MSMQ transport, binary encoding,
WS-* support
netNamedPipesBinding IPC transport, binary encoding,
WS-* support
netTcpRelayBinding TCP transport with Windows Azure,
WS-* support
netTcpContextBinding TCP transport with context
correlation for Workflow Services
Configuring Binding in the Configuration File

<bindings>
<basicHttpBinding>
<binding name="NoCookies"
sendTimeout="00:10:00"
allowCookies="false">
<security mode="Transport"></security>
</binding>
</basicHttpBinding>
<netTcpBinding>
<binding name="bigMessagesWithTransaction"
sendTimeout="00:10:00"
maxReceivedMessageSize="1048576"
transactionFlow="true">
<security mode="Message"></security>
</binding>
</netTcpBinding>
</bindings>
Configuring Binding in Code

BasicHttpBinding NoCookiesBinding =
new
BasicHttpBinding(BasicHttpSecurityMode.Transport)
{
AllowCookies = false,
SendTimeout = TimeSpan.FromMinutes(10)
};

NetTcpBinding bigMessagesWithTransactionBinding =
new NetTcpBinding(SecurityMode.Message)
{
SendTimeout = TimeSpan.FromMinutes(10),
MaxReceivedMessageSize = 1048576
};
Creating a Custom Binding

Organize a custom binding as an ordered set of binding


elements

<customBinding>
<binding name="MyBinding"
sendTimeout="00:10:00">
<transactionFlow/>
<reliableSession ordered="true"/>
<security authenticationMode=
"AnonymousForCertificate"/>
<binaryMessageEncoding/>
<tcpTransport transferMode=
"StreamedResponse"/>
</binding>
</customBinding>
Defining an Endpoint

To define an endpoint, provide the address, binding,


and contract

<services>
<service name="Calculators.ComplexCalc">
<endpoint address="http://localhost:8080/complex"
binding="basicHttpBinding"
contract="calculators.IComplexCalc"/>
</service>
</services>

ServiceHost myHost = new ServiceHost(typeof(ComplexCalc));


myHost.AddServiceEndpoint(typeof(IComplexCalc),
new BasicHttpBinding(),
"http://localhost:8080/complex");
Creating a Service Host

A service host can be any Windows process

Information about the hosted services is written in


code or in a config file under <system.serviceModel>

The base class for all WCF service hosts is


ServiceHostBase

Services running under IIS, WAS, or AppFabric are


opened automatically

Other hosts require calling the Open method


Opening a Service Host

Initializing a host in code, or from configuration

ServiceHost myHost = new


ServiceHost(typeof(ComplexCalc));
//Read the hosted service information from
//the configuration
myHost.Open();

ServiceHost myHost = new


ServiceHost(typeof(ComplexCalc));
myHost.AddServiceEndpoint(typeof(IComplexCalc),
new BasicHttpBinding(),
"http://localhost:8080/complex");
//The hosted service information is written in code
myHost.Open();
Lesson 3: WCF Behaviors

Dispatchers and the Channel Stack

Using Behaviors to Configure WCF Dispatchers

Defining Behaviors in the Configuration File

Defining Behaviors in Code


Dispatchers and the Channel Stack

The channel stack needs to be extended to allow


configuration of additional aspects

After the channel pipeline there are several dispatchers


that process the messages

These dispatchers can be used to adjust the service


behavior in aspects like:
Instancing
Concurrency
Throttling
Security
Serialization
many others
Using Behaviors to Configure WCF Dispatchers

The mechanism to configure the dispatchers is called


behaviors

WCF introduces a wide collection of predefined


behaviors

Some behaviors can be attached in code using


attributes while other can also be written in the
configuration file

Behaviors are one of the major extensibility points of


WCF
Defining Behaviors in the Configuration File

<behaviors>
<serviceBehaviors>
<behavior name="limitCalls">
<serviceThrottling maxConcurrentCalls="10"/>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug
includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>

<service name="Calculators.ComplexCalc"
behaviorConfiguration="limitCalls">
<endpoint>. . .</endpoint>
</service>
Defining Behaviors in Code

Some behaviors are developer-oriented while others


are administrator-oriented

Developer Administrator
Instancing Throttling
Concurrency Security credentials
Serialization Exposing metadata

Developer-oriented behaviors are written in code using


attributes

[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]
public class ComplexCalc : IComplexCalc {. . .}
Lesson 4: Consuming WCF Services

The Proxy Pattern

Adding a Service Reference

Service Reference Contents

Demonstration: Creating a WCF Client

Building a Proxy Using a Channel Factory

Using Channel Factories Correctly

Demonstration: Using a Channel Factory


The Proxy Pattern

A proxy reflects an entity over a technology boundary

The proxy translates method calls to a messages


exchange over the relevant transport

var i = prox.Add(2,3);

Add Add
Sub Sub
5 2+3
Mul Mul
Div Div
Adding a Service Reference

Use the Add Service Reference tool in Visual Studio


2010 to auto-generate the proxy class
Service Reference Contents

Adding a service reference generates a proxy class

All the service contracts and data contracts are


reflected in the client project

The WCF client configuration section is appended to the


clients configuration file

The proxy is named after the service with a Client


suffix (for example CalculatorClient)
Demonstration: Creating a WCF Client

Add service
reference

Write code and


consume the proxy
Creating a WCF client

Build and debug the


solution
Building a Proxy Using a Channel Factory

A proxy to a WCF service can be built without Visual


Studio 2010 and automatic code generation

Create a ChannelFactory<T>

Create a channel

var chf = new


ChannelFactory<IComplexCalc>("ClientEndpointName");
IComplexCalc prox = chf.CreateChannel();
Using Channel Factories Correctly

When using a channel factory you are


responsible for:
Setting the client configuration
Importing the service and data contracts
Disposing of the proxy correctly

ICommunicationObject obj = (ICommunicationObject)proxy;


if (obj.State == CommunicationState.Opened)
{
obj.Close();
}
Demonstration: Using a Channel Factory

Create and consume


the proxy

Write the config


Creating a WCF client
using a channel
factory

Build and debug the


solution
Lab: Service Development Life Cycle
Exercise 1: Defining Service and Data Contracts

Exercise 2: Creating a Service Implementation

Exercise 3: Configuring the Service

Exercise 4: Consuming the Service Using Channel Factories

Exercise 5: Consuming the Service Using a Service Reference

Logon information

Virtual machine 10263A-SVR1

User name Administrator

Password Pa$$w0rd

Estimated time: 90 minutes


Lab Scenario
Lab Architecture
Lab Review
Review Questions
Describe the service creation cycle

From which class should the service implementation derive?

Which class is used to create a host?

Where are endpoints defined?

Describe two methods of proxy creation


Module Review and Takeaways
Review Questions

Best Practices

Das könnte Ihnen auch gefallen