Is there a generally accepted way to avoid having to use KnownType attributes on WCF services? I\'ve been doing some research, and it looks like there are two options:
I wanted to post what seems to be the simplest, most elegant solution that I can think of so far. If another answer comes along that's better, I'll go with that. But for now, this worked well.
The base class, with only one KnownType
attribute, pointing to a method called DerivedTypes()
:
[KnownType("DerivedTypes")]
[DataContract]
public abstract class TaskBase : EntityBase
{
// other class members here
private static Type[] DerivedTypes()
{
return typeof(TaskBase).GetDerivedTypes(Assembly.GetExecutingAssembly()).ToArray();
}
}
The GetDerivedTypes()
method, in a separate ReflectionUtility class:
public static IEnumerable GetDerivedTypes(this Type baseType, Assembly assembly)
{
var types = from t in assembly.GetTypes()
where t.IsSubclassOf(baseType)
select t;
return types;
}