I have a large collection of domain models in a core library which also contains methods for getting various sets of models. Multiple WCF service projects reference this library and publish the sets e.g.
GetProducts(int categoryId)
My initial approach was to decorate the domain models with DataContract and DataMember attributes and return them from the WCF service methods. However I see the flaw in that approach as now some services want different model properties serialised to others.
I think I have 2 choices:
In each WCF project create DTO classes with necessary properties and attributes for that project and return these from the service methods. Construct the DTOs from the domain models. This looks like the "right" approach but extremely time consuming to set up and maintain as domain models expand.
Write my own xml serialiser that dynamically chooses which properties of the domain models to serialise at runtime, depending on the project. I have no idea if this is even possible!
(I also considered the "trick" of setting the properties I didn't want serialising to their default value then changing them back after serialisation but its too fiddly and smells bad)
Is there any other approach or is there a way to reduce the manual work involved in #1?
Approach #1 in the right one. Design the DTOs so that they meet the requirements of the client and make sure it works fine with WCF.
The mapping from domain objects to DTOs is something that can be greatly simplified by using an object to object mapper. AutoMapper is a common choice in .NET projects. It is flexible and has good performance.