Generally accepted way to avoid KnownType attribute for every derived class

前端 未结 6 1405
情书的邮戳
情书的邮戳 2020-12-14 17:19

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:

6条回答
  •  粉色の甜心
    2020-12-14 18:20

    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;
    }
    

提交回复
热议问题