views:

137

answers:

2

I've been pretty confused on one point in design of DataContracts for serialization.

Say I have an object (e.g. a Customer) and it exposes a collection property (e.g. an AddressCollection named Addresses). Framework design guidelines dictate that I should not expose a public mutator for the property, i.e., the collection property should have a get and no set, and instead a public set method (public void SetAddresses(IEnumerable< Address> addresses)).

But if I want to serialize that object, and I anticipate that I will be in a partial-trust environment, do I have to add a public setter to the property so it can be properly deserialized?

Furthermore, if the collection has nothing in it on serialization, and since the default constructor isn't called by the DataContractSerializer, I'm pretty sure the collection isn't set at all and is left as null. I could use the OnSerializing attribute to initialize the collection, but then that method would also have to be public in a partial-trust scenario, wouldn't it? And that's even uglier.

Does anyone know the appropriate guidance here?

Thanks much.

A: 

If you really would like to protect your Domain Model you may want to consider adding some data transfer objects to your solution. That way you can serialize just what you need and manipulate the domain internally.

Adam Fyles
+1  A: 

Yup, it's tried and true OO thinking meets new tools. :) I like to think of it in terms of a DTO pattern. I set up my true business objects as close to mutator-free as humanly possible, then I use a set of DTO objects that are designed to be serialized (public properties, blank constructors, etc.) It's not an ideal solution, but I have found that if you try and mix very rich object sets with serialization, it can get ugly. Better to separate them out.

JP Alioto