Click here to Skip to main content
15,887,477 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Implementing KnownType Attribute

Rate me:
Please Sign up or sign in to vote.
4.80/5 (3 votes)
10 Sep 2010CPOL 37.4K   162   7   2
Why and How to implement KnownType Attribute in WCF Service


Problem:


I have wrote my class library for my business logic. When I try to implement, using Abstract Factory, my service is giving error!. 


For the sake of simplicity consider the following example: 


Fig-1.gif
Internally I could have use Interface Segregation Principle and write a method like this.

C#
internal ITeam GetMyTeamForInternalUse(int tn) 


WCF won't allow me to return interface, so made the changes as bellow.




C#
public Team GetTeam(int teamNumber)  


If the teamNumber is 0 then new Team object will return, if it's 1 new TeamX object will return and If it's 2 new TeamY object will return. This is the simple login in my service.

Here is my service logic. As you can see I'm returning base class object. The child classes inherit from Team class are not known to WCF. For this we need to use KnowType Attribute. Please see the solution section.

C#
namespace KnownTypeService
{
    public classMyService : IMyService
    {        
        public Team GetTeam(int teamNumber)
        {

            if(teamNumber == 0)
                return newTeam { Name = "Normal Team", Project = ",Production Support"};

            else if(teamNumber == 1)
                return newTeamX { Name = "Resarch Team", Project = "Technology Research",TeamXMember = "Proud to be X"};

            else if(teamNumber == 2)
                return newTeamY { Name = "Management Team", Project = "Issue Fix", TeamYMember = "Manage everyone"};

            else return null
        }
    }
}

Solution

For solving above problem the returning class, in our case, Team, has to be attributed as follows:  



C#
/*This code is mandatory other wise service will throw error for value 1 & 2*/
   [KnownType(typeofTeamX))]
   [KnownType(typeofTeamY))]
   [DataContract]
   public class Team : ITeam


It will work fine now

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Automation Anywhere
India India
Working as Lead Architect at Automation Anywhere.

Comments and Discussions

 
GeneralReason for my vote of 5 This is a test vote. Relax - I will ... Pin
Chris Maunder11-Sep-10 15:39
cofounderChris Maunder11-Sep-10 15:39 
GeneralReason for my vote of 2 This is a test vote. Relax - I will ... Pin
Chris Maunder11-Sep-10 15:39
cofounderChris Maunder11-Sep-10 15:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.