Introduction
This post is all about WCF serialization surprising behavior
As you may know while passing complex type as parameter for WCF will be serialized using DataContractSerializer.
One thing you should notice about the serialization process is that unlike XmlSerializer it will not call the constructor or field initialization.
The code sample for this post is available here
What it all about
If you declare the following contract
[DataContract]
public class MyCompositeType
{
private Guid m_id1 = Guid.NewGuid ();<span style="COLOR: #009900">
public MyCompositeType () <span style="COLOR: #009900">
{
Id2 = Guid.NewGuid ();
}
public Guid Id1
{
get { return m_id1; }
}
public Guid Id2 { get; private set; }
[DataMember]
public string StringValue { get; set; }
}
Do not expect that the ids (which is not data member) be initialized on the other side of the serialization process
If we having the following service implementation:
public MyCompositeType GetDataUsingDataContract ( MyCompositeType composite )
{
composite.StringValue += " : " + composite.Id1.ToString () + " : " + composite.Id2.ToString ();
return composite;
}
The call it from the client look like this:
static void Main ( string[] args )
{
MyProxy.SampleServiceClient svc = new MyProxy.SampleServiceClient ();
var composite = new MyCompositeType { StringValue = "Test" };
Console.WriteLine ("Id1 = {0} \nId2 = {1}",
composite.Id1.ToString (), composite.Id2.ToString ());
var response = svc.GetDataUsingDataContract (composite);
Console.WriteLine (response.StringValue);
Console.WriteLine ("Id1 = {0} \nId2 = {1}",
response.Id1.ToString (), response.Id2.ToString ());
Console.ReadLine ();
}
The ids will be initialized to none empty Guid only on the client side
Both at the server and the response ids will be empry
You can place brake point on the complex type constructor at the server side
but it will never stop there.