Search

Nov 27, 2013

Exposing property as OperationContract in WCF

Hello All,

I would like to share thing which I just learn today J

In WCF usually we work with operation contract i.e. methods. I was trying to expose property not a method. I found solution and here is the way it should be

Simple Service Contract

clip_image001

Contract Implementation

clip_image002

Nothing fancy, and here is client to call this service and its output

clip_image003

So before we go further, I would like to make you clear about what we are going to do.. So requirement is I don’t want to change DoWork signature, but still want to add some additional information which DoWork should use if available, means a kind of optional parameter I would like to add.

For that I need to add property and get it exposed into client. So my new service contract will something similar as bellow

clip_image004

You can see, one new property Message added with only set, as I want to be as one-way. To Expose property you have to write OperationContract attribute ot get or set not on top of member just we do with method.

Now change little bit in logic to use Message if it’s there if not then behave normally.

clip_image005

After updating reference, I can see WCF internally convert my Message property into method by adding set_ prefix.

clip_image006

Let’s set message and will call my work method again.

clip_image007

Demm it, doesn’t work! It’s fairly simple and straightforward!!! Where is the issue? @#$%$@@#$

In debug I can see message is set property to my private variable…

clip_image008

but when I call DoWork I don’t see value is persist!

clip_image009

Its WCF setting that we are missing, WCF by default does not keep context for ever… we have to tell them to keep it alive per session, per call (default) or single. Per session requires some more extra efforts to get it working… let’s keep simple by using Single, it’s part of service behavior, lets add and see if that works…

Add attribute…

clip_image010

And let’s make call from client again..

clip_image011

Yes… we got it working J now as we make context mode to single, subsequent call of DoWork will return same result. That means its consider as a kind of Static

clip_image012

If we switch context mode to session then following code will behaves as expected

clip_image013

Hope this helps.