Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF DataContracts

I have a WCF service hosted for internal clients - we have control of all the clients. We will therefore be using a data contracts library to negate the need for proxy generation. I would like to use some readonly properties and have some datacontracts without default constructors. Thanks for your help...

like image 476
Craig Wilson Avatar asked Oct 05 '08 21:10

Craig Wilson


People also ask

Is DataContract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.

What is DataContract in WCF?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is DataMember in WCF?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.

Why do we use DataContract in C#?

It is used to get or set the name for DataContract attribute of this type. It is used to get or set the order of serialization and deserialization of a member. It instructs the serialization engine that member must be present while reading or deserializing. It gets or sets the DataMember name.


1 Answers

Readonly properties are fine as long as you mark the (non-readonly) field as the [DataMember], not the property. Unlike XmlSerializer, IIRC DataContractSerializer doesn't use the default ctor - it uses a separate reflection mechanism to create uninitialized instances. Except on mono's "Olive" (WCF port), where it does use the default ctor (at the moment, or at some point in the recent past).

Example:

using System;
using System.IO;
using System.Runtime.Serialization;
[DataContract]
class Foo
{
    [DataMember(Name="Bar")]
    private string bar;

    public string Bar { get { return bar; } }

    public Foo(string bar) { this.bar = bar; }
}
static class Program
{
    static void Main()
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Foo));
        MemoryStream ms = new MemoryStream();
        Foo orig = new Foo("abc");
        dcs.WriteObject(ms, orig);
        ms.Position = 0;
        Foo clone = (Foo)dcs.ReadObject(ms);
        Console.WriteLine(clone.Bar);
    }
}
like image 75
Marc Gravell Avatar answered Oct 05 '22 08:10

Marc Gravell