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

风格不统一 提交于 2019-12-03 06:28:56

问题


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:


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.



来源:https://stackoverflow.com/questions/2455244/what-is-the-difference-in-wcf-when-using-knowntype-and-serviceknowntype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!