Search code examples
wcfdata-annotationswcfserviceclient

Publish DataAnnotation attributes in a WCF service, and regenerate them at the consumer proxy classes?


I have a WCF that exposes various classes. I applied DataAnnotation attributes on some of the properties.

I want them to be generated in the consumer project as well, is there a way to do this?


Solution

  • No. WCF is a message-based system, so all that connects your client and your service are the XML-serialized messages (and their format) on the wire.

    When you create a proxy, all the WCF runtime can do is re-create your data structures so that when you XML serialize one of your client-side classes, the representation on the wire will be the same as with the server-side class.

    The client has no way of "reaching" into the server's bowels and find out about .NET specific stuff like data annotations...

    That said: if you control both ends of the communication, e.g. you write both server and client, there's another approach you could take:

    • create a separate class library assembly with your service and data contracts (just the contracts)
    • reference that common shared assembly from both your server code, as well as your client side project, before you add the service reference
    • when you add a service reference, by default, the WCF runtime will reuse existing types; so if it add a service reference to your service, and you need a data class MyData and that class exists in the referenced shared assembly, the WCF runtime will reuse it (instead of re-creating a new, separate client-side proxy class)

    With this "trick", you can share certain classes (e.g. data classes) between service and client - including all your .NET attributes on it