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...
No, the DataContractAttribute is not required - WCF will infer serialization rules.
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With