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 Data Contract

Data Contract Hierarchy

 

  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

Mixing of DataContract and Serilizable

One problem in WCF

Follow the below code,

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



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

Contract and classes

Error Service implantation

 


 

 


 

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

  1. The KnownTypeAttribute allows designating the sub class. 

Example

 

  1. 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.
  2. WCF includes sub class in metadata such that client can also pass the sub class instead of base class. 

ServiceKnownTypeAttribute


 

ServiceKnownTypeAttribute class

 

 

 

 

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s