Using Data Contracts in WCF

. Sunday, January 8, 2012
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

Using Data Contracts
Data contracts describe the structure of data passed in and out of the service. In the case of
simple, known types such as integers and strings, WCF applies a default contract; if your serv-
ice exposes only simple types, you do not need to define a data contract. The CustomerService
contract shown in the previous listing, however, exposes a CustomerDatatype, which is a com-
plex type and, therefore, requires a data contract.
Again, WCF makes it easy to define a data contract by providing several attributes that you
can use to decorate the CustomerDatatype:

// Also need a reference to System.Runtime.Serialization.dll
using System.Runtime.Serialization;
[DataContract]
public class CustomerData
{
[DataMember]public string FirstName;
[DataMember]public string LastName;
[DataMember]public string Email;
}
As you can see, the data contract attributes are analogous to the XML serializer attributes
such as XmlElementand XmlAttribute. However, unlike today’s Web Services, WCF does not by
default use the XmlSerializer to serialize complex types. Instead it uses XmlFormatter, which
has better support for versioning and understands these new DataContractand DataMember
attributes. You can explicitly specify the desired formatter using the FormatModeparameter of
the ServiceContract attribute as we show in the following example.
[ServiceContract(Namespace="http://indigorocks/", Name="CustomerService",
FormatMode = ContractFormatMode.XmlFormatter)]
interface ICustomerService
{ ... }

0 comments: