Laurence
Laurence

Reputation: 1020

Best approach to exposing data from domain models thru WCF services

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:

  1. 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.

  2. 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?

Upvotes: 1

Views: 296

Answers (2)

Batavia
Batavia

Reputation: 2497

There is a 2b variant. If you mark the objects with [DataContract] and properties with [DataMember] attributes only those will be serialized.

i've used this approach with some success. The question really becomes are it always the same properties that you want to serialize. For example if you have access to the address object and then everything in the address class is publicly visible this is viable. Even if you keep internally a set of geo coordinates for some distance algorithm that you don't expose.

However if some people do, and some people don't have access to a customer's full creditcard number then this approach will be a problem if you try to serialize the customer. (access to a customer's address can still be separately determined if address is a separate object).

Maybe not the best example from a ddd perspective since address probally wouldn't be an entity but i hope you understand my considerations

Upvotes: 0

theDmi
theDmi

Reputation: 18034

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.

Upvotes: 1

Related Questions