Search code examples
.netwcfabstract-classknown-types

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?


Solution

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