The properties associated with the DataMember attributes only determine what will be included in the generated WSDL / XSD. The client will generate its own wsdl / xsd based classes for use with the service. It does not use the same classes that are used on the server.
This is why you will not get:
- any constructors defined in the
DataContract class - any private
[DataMember] properties / fields (the client will always generate public properties / fields) - any behavior defined in the
DataContract class
Imagine a scenario when a java client wants to connect to your service. Do you expect Java classes to be generated using the same constructor? What about the [OnDeserialized] attributes? What about a java script client or python client?
When you start thinking about it this way, you begin to understand why you cannot have what you want (at least not exchanging libraries between the client and server).
The reality is that you cannot force the client to have classes that always have default values, and you cannot always send valid data back to the client, the client can always just send a message containing garbage if it wants. You have little control over some aspects of the message using IsRequired and 'EmitDefaultValue`, which will add checks in xsd to make sure that something is present in the message, but you will need to perform a check on the server, you can assume that you are returning objects will be checked.
My suggestion was to create a DTO from your domain objects to send over wires that do not contain any verification, they are just simple packages for storing data. Then create factories to turn your domain objects into DTO and DTO into client objects. factory simply accepts a DTO and passes members to the constructor of the domain object. Then your validation logic can live in the constructor of the domain object where it belongs. With the approach that you are currently using, you probably end up twisting the test slightly so that it can be performed both from the constructor and from the [OnDeserialized] method.
Sam holder
source share