开发者

KnownType for all derived types of an abstract class?

We have an abstract class that is the base for a开发者_开发知识库 number of different requests we send over a WCF service. It's an ugly heinous hack that every time we add a new request we have to remember to add the [KnownType] attribute to this base class.

Is there a way to tell the DataContractSerializer to treat ALL derivations of this abstract type as a KnownType?


I had the same problem in a WCF service and did the following "less heinous" hack to work around the known type limitation. I'm outlining just for the sake of showing alternate options, it's up to you to decide if it's better or not.

  1. At service startup, load via reflection the types you want to expose. E.g. if all your WCF-exposed entities derive from a common abstract base (or more), load all types from the assembly they're supposed to be located into. Cache these types statically for performance reasons.

  2. Create a static method that returns the said cached types, with the following signature: public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)

  3. Mark the WCF interface with the following attribute [ServiceKnownType("GetKnownTypes", typeof(StaticClassThatCachesTypes))]

This should give you automatic exposing of all types that are or will be derived from the base class(es) of your choice, as long as the future developer(s) place them in the correct assembly.


Another option in addition to the one given by Dan C. is to switch to the NetDataContractSerializer - it does not require known type declarations, since it is tightly coupled to the exact contract implementation, so you'll need to share the assembly which contains the types between the client and the server - and you'll definitely lose interoperability in this scenario. There are a few posts about doing that (I've seen this one pop up in google/bing results often).


Here is an example of doing this with PostSharp. Look towards the bottom of the post.


This is an example of achieving this with IL Weaving using Fody/Mono.Cecil.

Basically, this is a Fody extension that injects KnownTypeAttributes during build time using IL Weaving.

During the build pipeline, the extension locates all base classes marked with the KnowsDeriveTypes attribute (Part of the extension) and it will add the KnownTypeAttribute over all classes that derive (not necessarily directly) from one of the above base classes (with the KnowsDeriveTyepsAttribute).

This is another mirror for the post and here you can find the Github repo for the extension.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜