65.9K
CodeProject is changing. Read more.
Home

Implementing KnownType Attribute

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (3 votes)

Sep 10, 2010

CPOL
viewsIcon

38069

downloadIcon

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.
internal ITeam GetMyTeamForInternalUse(int tn) 

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

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.
			
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:  

 /*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