DataContractSerializer’s ServiceKnownType & KnownType attributes

February 17, 2009

When we use WCF in conjunction with DataContractSerializer one notices that there are 2 attributes you can use: ServiceKnownTypeAttribute and KnownTypeAttribute

KnownTypeAttribute:

Let’s say you have the following classes:

1. Person

2. Employee – derives from Person

If you mark each class with the DataContract attribute and create a service operation that returns a Person type, you will be able to return a Person, but not an Employee. If you try to return the latter, you’ll receive either a serialization error (if you catch it on the server side) or a strange client-side error.

To fix this problem you decorate your base class (Person) with the KnownType attribute to tell the outside world (meaning the service contract and the serializer) what a Person can look like, such as:

[KnownType(typeof(Employee))]
[DataContract]
public class Person {…}

Once you decorate your Person class with every known derived type, you can return these types from your service (or receive these types). Be sure to update your client’s service reference to get these new definitions.

To conclude – Use KnownType because if you don’t tell the outside world what to expect, don’t be surprised if they don’t understand that you meant to send the base but sent the derived instead…

For more information: KnownTypeAttribute Class

ServiceKnownType:

The above case was useful when your service used the base class as the input/output type of the operation, but what if your operation returns an arbitrary “object”? or just a simple hashtable?

In this case you can’t use KnownType because this attribute applies to data classes, not to methods or services.

If your operation receives/returns an arbitrary type, use the ServiceKnownType attribute to decorate either the service or one of it’s operations and state which types the service can receive/return (or in other words – which data contracts the service is aware of).

For more information: ServiceKnownTypeAttribute Class

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*