Objective
This article will explain
- Data Contract hierarchy
- How base class and sub class are getting exposed in WCF?
- What is Known Type attribute
- Mixing of sterilization and Data Contract
Data Contract Hierarchy
-
If any class in hierarchy is not attributed as [DataContract] or [serilizable] then InvalidDataContractException will occur at service run time
-
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,
- There are two classes in hierarchy
-
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
- The solution is to explicitly tell WCF about the sub class to the base class.
-
This is done using KnownType Attribute class.
This class is defined as below in System.Runtime.Serilization namespace
-
The KnownTypeAttribute allows designating the sub class.
Example
- 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.
-
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.
Leave a Reply