Search code examples
c#wcf

WCF passing a custom object to client and running its methods


This is as much a design as a technical question. I'm not sure I am doing this right...

I have a WCF API which communicates with a DB and passes back a Person object (which is defined in a separate .dll) This has both methods and attributes. The object is being sent from the WCF to the calling client.

I want to call the Person's methods on the client. I understand that these cannot be sent downstream from the API. However, if I reference the same .dll that the WCF uses should I be able to cast the API Person to a .dll Person then run the methods?

I hope it is clear what I am trying to achieve.


Solution

  • WCF supports the ability to re-use references that are already included in the project. In this sense, you can create a contracts assembly (an assembly that contains your thin domain models (e.g. Person etc) which you can add your own logic to.

    You can then add assembly to both your WCF service, and the calling client projects, and instruct WCF to re-use any existing references. This way, what is pulled back from your service is deserialised into local copy of a Person, but not a Person that would generated as a proxy, you actually get a full instance, on which you can perform method calls.

    Don't forget through, you are marshalling by value in this case. Any changes you make to the Person instance are local to the client only, you would need to pass it back upstream to your WCF service again (through serialisation) for the service to recognise any changes and act accordingly.