Friday, 22 May 2015

Associating KnownType in WCF

There are 4 different ways to associate [KnownType]

1-) Use KnownType attribute on base type,This option is global, that is all service contracts and all operation contracts will respect the known types.


[KnownType(typeof(PartTimeEmployee))]
    [KnownType(typeof(FullTimeEmployee))]
    [DataContract]
    public class Employee
    {
        [DataMember]
        public int empID { get; set; }
        [DataMember]
        public string empName { get; set; }
        [DataMember]
        public string empAddress { get; set; }    
     
    }
    public class PartTimeEmployee : Employee
    {    
        public int Salary { get; set; }
    }
    public class FullTimeEmployee : Employee
    {    
        public int HourWorked { get; set; }      
        public int HourPaid { get; set; }
    }


2-) Apply [ServiceKnownType] attribute on the [ServiceContract] : with this option the known types are respected by all operation contracts within this service contract only.

[ServiceKnownType(typeof(PartTimeEmployee))]
    [ServiceKnownType(typeof(FullTimeEmployee))]
    [ServiceContract]  
    public interface IService1
    {

        [OperationContract]
        void saveEmoloyee(Employee emp);

     
        [OperationContract]
        Employee getEmoloyee(int id);
     
    }


3-) If you want even more granual control, then apply [ServiceKnownType] attribute on specific operation contracts. With this option, only the operation contracts that are decorated with ServiceKnownType attribute.

[ServiceContract]  
    public interface IService1
    {

        [OperationContract]
        void saveEmoloyee(Employee emp);

        [ServiceKnownType(typeof(PartTimeEmployee))]
        [ServiceKnownType(typeof(FullTimeEmployee))]
        [OperationContract]
        Employee getEmoloyee(int id);
     
    }

4-) Specify known types in configuration file. this is equivalent to applying known type attribute on base typpe means this is applicable globally.

Related Post :

Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault

No comments:

Post a Comment