Data Contract Hierarchy in WCF


Objective:

This article will explain

  1. Data Contract hierarchy
  2. How base class and sub class are getting exposed in WCF?
  3. What is Known Type attribute
  4. Mixing of sterilization and DataContract

Data Contract Hierarchy
image1.gif

  1. If any class in hierarchy is not attributed as [DataContract] or [serilizable] then InvalidDataContractException will occur at service run time.
  2. WCF allows mixing [DataContract] and [Serilizable] attribute. But [Serilizable] should be at the root of the DataContract hierarchy.

    Examples:

    image2.gif

Mixing of DataContract and Serilizable

image3.gif

Follow the below code,

  1. There are two classes in hierarchy
  2. Base class is referring instance of derive class. This is perfectly valid.

    image4.gif

    image5.gif

    image6.gif

Let us try to refer derive child class in base class,

Contract and classes

image7.gif

Error Service implantation

image8.gif

image9.gif

How to solve this problem?

KnownTypeAttribute

  1. The solution is to explicitly tell WCF about the sub class to the base class.
  2. This is done using KnownType Attribute class.

    This class is defined as below in System.Runtime.Serilization namespace.

    image10.gif
     
  3. The KnownTypeAttribute allows designating the sub class.

    Example

    image11.gif
     
  4. On the host side the KnownTypeAttribute affects all contracts and operations using the base class across all services and endpoints. This allows accepting subclass instead of base class.
  5. WCF includes sub class in metadata such that client can also pass the sub class instead of base class.

ServiceKnownTypeAttribute
image12.gif


ServiceKnownTypeAttribute class

image13.gif

image14.gif

image15.gif

ServiceKnownType could be applied on a particular service operation or to entire service contract. 

Up Next
    Ebook Download
    View all
    Learn
    View all