What is the difference in WCF when using KnownType and ServiceKnownType?
Asked Answered
P

1

25

I have a service that returns an array of animal but the list can contain cats, dogs, etc, which all extend animal. I know I need to use either the KnownType or ServiceKnownType attribute, and on the entity class or the service class, respectively.

What is the difference between the 2 attributes? I prefer the ServiceKnownType because it is applied on the service, exactly where it is needed and called for, as opposed to KnownType which is applied on my entity. To me applying it on the entity class means knowing too far ahead how my entity class is being used.

For now I have it on my entity and it works like a charm, but I am looking for guidance here as to best practices and usefullness.

Penner answered 16/3, 2010 at 14:39 Comment(0)
P
43

They do the same thing, ultimately - but on a different scope.

[ServiceKnownType] defines a class hierarchy for all methods on this service, or a single method on the service (depending on where you put the attribute). So in this case, this type hierarchy will only be valid and applicable for this service or maybe even just a single method in that service contract.

[KnownType] does the same thing - but on the underlying data contracts. Any service that will be using this data contract now also "inherits" all those potential descendant classes - which might or might not be what you want.

So really - it's just a matter of what scope you want to apply a given declaration to - putting it on the data contract makes it sort of a "global" type hiearchy, while using [ServiceKnownType] allows you to define something that's valid only for one service contract or even just one (or several) methods on that service contract.

Pops answered 16/3, 2010 at 14:39 Comment(2)
Thank you. That is what I was thinking and i am going to put it at the operation contract level.Penner
BTW - the reason that I marked Matt's answer as the accepted one is because of the link that he provides that goes into it in more depth. I do like your answer though - it says it in less words.Penner

© 2022 - 2024 — McMap. All rights reserved.