Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding methods to DataContract objects for WCF

Tags:

wcf

Are DataContracts in WCF nothing more than DTOs? I was reading up about WCF and just had a couple of thoughts. It would be nice if some of the DataContract objects could have methods on them so that the client could do basic things with them before or after sending or retrieving back to the service.

To me this just doesn't seem possible or logical. I could be wrong, I learn new things everyday. So would the next best thing be to treat DataContracts as DTOs and provide libraries for the clients that would create real objects from the DTOs. Objects that would contain methods.

Any guidance would be really appreciated.

like image 838
uriDium Avatar asked Dec 12 '22 19:12

uriDium


2 Answers

Not sure if I correctly understood your answer, so correct me if I'm wrong.

You can create a class library with your DataContracts classes and share the library between the client and server. In this way class marked [DataContract] will have methods (behavior) and [DataMember] fields/properties (state).

When you will pass such objects between client and server via WCF state will be persisted, but since class library is shared you will have methods on both sides.

like image 167
Insomniac Avatar answered Jan 21 '23 09:01

Insomniac


DTOs that are decorated as DataContract classes are real objects. They can have methods in them, but the methods are not part of the serialization process.

The main time this will cause you issues is when:

  • you are relying on the generated proxy version of the DataContract objects (like when you have a Silverlight client calling a WCF service, or you are calling a third party service that you have no access to the code or its libraries). The generated proxy versions will not have the methods in them, just the DataMember properties. The way to get round that is to use objects from a shared library (as already mentioned by @Insomniac).

  • your properties in the DataContract objects are more than just a simple get/set operation, i.e. you may have included some logic to do other operations when a property value is set. In this case even the proxy generated version will not have that logic included. The ways to get round this is to either have the shared library, or have a partial class on the client side that extends the proxy generated class.

like image 26
slugster Avatar answered Jan 21 '23 08:01

slugster