Understanding ServiceKnownType in WCF

Posted by SLC on Stack Overflow See other posts from Stack Overflow or by SLC
Published on 2010-05-03T12:45:05Z Indexed on 2010/05/03 12:48 UTC
Read the original article Hit count: 910

Filed under:
|

I am having a little trouble understanding ServiceKnownType in WCF.

Taken from this blog, the following code does not work:

[DataContract(Namespace = “http://mycompany.com/”)]
public class Shape{…}

[DataContract(Namespace = “http://mycompany.com/”)]
public class Circle : Shape {…}

[ServiceContract]
public interface IMyServer
{
    [OperationContract]
    bool AddShape(Shape shape);
}

.

IMyServer client = new ChannelFactory<IMyServer>(binding, endPoint).CreateChannel();

client.AddShape(new Circle());

The reason it doesn't work is because you are trying to add a circle, but the servicecontract only allows a Shape. You are supposed to do something with knowntypes, but I am a bit confused about how that works.

Since that code is in the service, why doesn't it know automatically that a Circle is derived from Shape? Additionally, what does ServiceKnownType actually do?

When ServiceKnownType is put below the DataContract, apparently that makes it work. I am guessing it says hey, this particular object type called Shape can also be a Circle. I am having trouble understanding why it would do it this way around, because if you add a new type like Square you are going to have to add that too, wouldn't it make sense if it cannot infer it, to put the KnownType onto the Square rather than the Shape? So the Square says hey, I am a Shape, and you don't have to fiddle with the Shape class?

© Stack Overflow or respective owner

Related posts about wcf

Related posts about serviceknowntype