From MSDN:
New complex types that you create must have a data contract defined for them in order to be serializable. This is normally done by applying the DataContractAttribute attribute to the type. This attribute can be applied to classes, structures, and enumerations. The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member; that is, it should be serialized.
Using Data Contracts
Our old friend, XmlSerializer, uses an opt-out strategy for defining members that are not to be serialized. WCF's DataContractSerializer, on the other hand, offers an Opt-In approach. What is basically means is that you have to be explicit about exactly what is included in the contract. Properties are no longer "guilty by association," so to speak.
For example:
// Serializable via the DataContractSerializer
[DataContract]
public class Person
{
[DataMember] private string WorstFear;
[DataMember] public string Name { get; set; }
[DataMember] public int Age { get; set; }
}
// Not serializable via DataContractSerializer
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
When it comes to Facebook Beacon, I love Opt-In. When it comes to WCF Data Contract, not so much. Now I have to decide "Do I want this stuff to *be* my domain model?" I *really* don't want to duplicate the model, once for the data contract, and once for the problem domain. But in most cases, I feel compelled down the path of DTOs. Most of the time, I am not a fan of DTOs. Linq's extension methods *do* make DTOs a bit more tolerable.
return People.Select(person => new PersonDTO(person));
Now.
My typical response to someone such as myself would be "Look. Just mark up your domain as your data contract. I mean, it's just a few attributes, right?"
Of course, I would reply with, "Yeah, and it's just a few attributes to mark up for object-relational mapping. Geez. When will it end?!?!"
(mmmm, cheesecake).
And then I would have to take a break from myself for a while. Eat better. Maybe start working out more. Take up a foreign language. Get a hip new haircut. Do some volunteer work. Travel like we always said we would. Re-center.
So.
Now that I have gotten that off my chest, I will tell you that there is at least one thing that I really love about data contracts, which is that you may expose private fields as Data Members for the purpose of serialization. Of course, that opens some surface area for confidentiality violations, but if the hackers are already deep enough that they can use DataContractSerializer, my guess is that that is the least of your worries.
Recent Comments