.NET Tips and Tricks

Blog archive

Using Properties in WCF Services

Scattered across all the services I've created, I must have 257 methods whose names begin with the word "Get" (e.g., GetCustomerData, GetOrdersForDate). And I typically have a corresponding method for accepting the data (e.g., UpdateCustomerData, SetOrders). I wouldn't write a class like that with two separate methods; I'd create a Property just called, for instance, CustomerData.

It turns out that you can use properties in a WCF Service: just put the OperationContract attributes on the property's getter and setter:

Public Property CustomerData As String
  <OperationContract()> _
  Get
    Return _CustData
  End Get
  <OperationContract()> _
  Set(value As String)
    _CustData = value
  End Set
End Property

Now, when I add a service reference to a consumer to generate the client-side proxy, I discover that I've only solved half of my problem. For the example above, the client-side proxy has two methods: get_CustomerData and set_CustomerData:

Dim cr As New CustomerService.CustomerServiceClient
sr.set_Data(custData)
Dim custData As CustomerData = sr.get_Data()

But on the service side, I no longer have two separate methods. Instead, the getter and setter for my data are now brought together in one Property. I'm OK with that.

If you're feeling very radical, you can write your property so that it accepts a parameter:

Public Property CustomerData(CustomerID As String) As String
  <OperationContract()> _
  Get
    Return _CustData
  End Get
  <OperationContract()> _
  Set(value As String)
    _CustData = value
  End Set
End Property

On the client-side, the proxy's get_ and set_ methods will now require a parameter:

Dim cr As New CustomerService.CustomerServiceClient
sr.set_Data("ALFKI", custData)
Dim custData As CustomerData = sr.get_Data("ALFKI")

Posted by Peter Vogel on 11/26/2012 at 1:16 PM


comments powered by Disqus

Reader Comments:

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.