Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Implementing KnownType Attribute

4.80/5 (3 votes)
10 Sep 2010CPOL 38.1K   162  
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)