Sharing custom types with client and services apps? Use WCF

One of the very difficult to solve problems in .NET client & web service solutions is sharing custom objects between the web service and the client.

Here’s the scenario.

You have a business layer with some serializable objects. Let’s say the namespace is “MyLovelyBAL” and the object is “MyLovelyObject”.

You have an operation in your web service that returns one of those objects.

Now you build a client, say a Windows Forms app (“MyWinApp”) that will call into that Web Service, and you are not savvy enough to use a tool like thinktecture’s WSCF. 🙂 Therefore you “Add Web Reference” and point to the web service you built. In doing so, you are asked to give a name to the proxy. Let’s call that “MyWSProxy”.

In your WIndows Forms app, you also have a reference to the assembly that contains MyLovelyBAL.MyLovelyObject.

Now it’s time to write some code.

You instantiate the proxy and request a lovelyobject.

Dim myproxy = New MyWSProxy.Service
Dim MyLovelyBAL.MyLovelyObject=myproxy.GetMyLovelyOBject

But it fails telling you that you can’t cast a MyWinApp.MyWSProxy.MyLovelyObject to a MyLovelyBAL.MyLovelyObject.

And then you will begin on a journey to hell, which might include reading this article on Schema Providers which is not for the feint of heart.

So just forget it. It’s 2007! We have WCF.

You can go into your project where you define the MyLovelyObject class and give it a DataContract attribute and give it’s properties (that you want to expose) DataMember attributes. Your interface operation (and any operations that implement it) will return a MyLovelyBAL.MyLovelyObject object.

And when you Add Service Reference to your windows forms app, there is no namespace replacement. A “MyLovelyObject” is always coming from MyLovelyBAL and this is oh, so lovely. The way it oughtta be!

You know I learned this the hard way. And I will be seeing Michele Leroux Bustamante tomorrow who will first bop me on the head for waiting so long to use WCF and the sit me down and have me read her fabulous book Learning WCF, (which I had in my hands long enough to raffle off at VTdotNET last week BOO HOO) cover to cover. It’s about time!

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

One thought on “Sharing custom types with client and services apps? Use WCF

  1. Another simple way to get the Winform done is to remove from the generated .vb(.cs) code for the WebService the class MyWinApp.MyWSProxy.MyLovelyObject and add an Import(using)MyLovelyBALto the beginning of the file

Leave a Reply to andrei ignat Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.