Thursday, November 26, 2009

WCF Contracts

3 Types of WCF Contracts:

  1. Service contracts: Maps class methods to WSDL services.

  2. Data contracts: Maps .NET classes to XML Schemas.

  3. Message contracts: Maps .NET classes to SOAP messages

I read through the section entitled "Service Contracts" and the message exchanges described follow standard communication patterns:

  • Request-Response (Synchronous and Asynchronous)

  • One-way

  • Duplex communication

I started working with the [DataContract] and [DataMember] attributes, which handle the manner in which model classes are mapped to the XSD ComplexType.

Very cool stuff.

Here's some sample code I wrote:

using System;
using System.ServiceModel;
using System.Runtime.Serialization;

namespace WinCommFoundation
[DataContract (Namespace="", Name="PersonComplexType")]
public class Person
[DataMember(Name = "FirstName", Order = 1, IsRequired = true)]
public String FirstName;

[DataMember(Name = "LastName", Order = 2, IsRequired = true)]
public String LastName;

[DataMember(Name = "ID", Order = 0, IsRequired = true)]
public Int64 PersonId;

[DataMember(Name = "Birthday", Order = 3, IsRequired = true)]
public DateTime DateOfBirth;

[DataMember(Name = "LastAccessDate", Order = 4, IsRequired = false)]
public DateTime LastAccessed;

public interface IPersonService
Person GetPerson();

public class PersonService : IPersonService
public Person GetPerson()
Person person = new Person();
person.PersonId = 0L;
person.FirstName = "John";
person.LastName = "Smith";
person.DateOfBirth = DateTime.Parse("1990-10-01");
person.LastAccessed = DateTime.Now;
return person;

public class Service
public static void Main(string[] args)
ServiceHost serviceHost = new ServiceHost(typeof(PersonService));

Console.WriteLine("Running PersonService, hit any key to end.");

And here is the corresponding App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<service name="WinCommFoundation.PersonService" behaviorConfiguration="personServiceBehavior">
<add baseAddress="http://localhost:8000/wcfTest"/>
<endpoint address=""
contract="WinCommFoundation.IPersonService" />
<endpoint address="mex"

<behavior name="personServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>

This created the following XSD:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema elementFormDefault="qualified" targetNamespace="" xmlns:xs="" xmlns:tns="">
<xs:complexType name="PersonComplexType">
<xs:element name="ID" type="xs:long" />
<xs:element name="FirstName" nillable="true" type="xs:string" />
<xs:element name="LastName" nillable="true" type="xs:string" />
<xs:element name="Birthday" type="xs:dateTime" />
<xs:element minOccurs="0" name="LastAccessDate" type="xs:dateTime" />
<xs:element name="PersonComplexType" nillable="true" type="tns:PersonComplexType" />

No comments:

Post a Comment