I have two classes as below:
[DataContract]
public class Address
{
[DataMember]
public string Line1
[DataMember]
public string Line2
[DataMember]
public string City
[DataMember]
public string State
[DataMember]
public string Zip
}
[DataContract]
public class Customer
{
public Customer()
{
CustomerAddress = new Address();
}
[DataMember]
public string FirstName
[DataMember]
public string LastName
[DataMember]
public Address CustomerAddress
}
What will happen if i generate proxy of my service that uses Customer class? If i understand the concept correctly then i think the constructor in the Customer class will not be called at the client side and it may give different behavior.
How do i get rid of that constructor in the Customer class and still have the CustomerAddress property of type Address so that it behaves as a dumb DTO object?
What is the general guideline or best practices that people use to avoid this situation?
If you use the default
DataContractSerializerto serialize your objects, then, yes, your constructor is not serialized, and any logic you may have in it will not be called by your client when the object is deserialized.Regarding your question about removing the constructor logic and having the nested
Addressclass be populated, that will be taken care of by theDataContractSerializer. If I have code like this:and then return that from a service method, that
Customerobject will be serialized properly along with theAddressinformation. The proxy on the client that’s generated will know aboutAddressand will be able to deserialize the stream coming from the service method to properly construct yourCustomerobject. YourCustomerwill be a dummy DTO — no logic, just properties.Check out Aaron Skonnard’s MSDN article on WCF Serialization where he talks about the DataContractSerializer.