What is the difference in WCF when using KnownType

2020-05-19 05:07发布

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.

1条回答
淡お忘
2楼-- · 2020-05-19 05:45

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.

查看更多
登录 后发表回答