Thursday, September 27, 2007

WCF inheritance in REST interop scenarios

I am writing Xml that needs to be consumable by any client that can make an HTTP request. I am also trying to write a service API that using inheritance so that i can have a method such as Accept() that can take any object derived from MyBaseClass.

The answer turned out to be easier than i thought, but it was a but of a struggle getting there as most answers are tuned toward your CLIENT also being a WCF client (which is the case in about 5% of my use cases).

The answer is to construct your Xml and use the Xml Schema type attribute to define the type of the object when passing it to a method that accepts its base class.

So if i have a web service method "Accept":

public void Accept(MyBaseClass val);

... and if i have the class MyClass : MyBaseClass , then in code i can simply write:

MyBaseClass bc = new MyBaseClass();

Now, to do the same in an XML REST POST WCF scenario, you construct the following Xml:

<val xmlns="" i="" i:type="MyClass"><br />...</val>

Notice the type attribute is used to state the derived class.

No comments: