Generally accepted way to avoid KnownType attribute for every derived class

前端 未结 6 1414
情书的邮戳
情书的邮戳 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:00

    Here's my variant on the accepted answer:

        private static IEnumerable GetKnownTypes() {
            Type baseType = typeof(MyBaseType);
            return AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(x => x.DefinedTypes)
                .Where(x => x.IsClass && !x.IsAbstract && x.GetCustomAttribute() != null && baseType.IsAssignableFrom(x));
        }
    

    The differences are:

    1. Looks at all loaded assemblies.
    2. Checks some bits we are interested in (DataContract I think is required if you're using DataContractJsonSerializer) such as being a concrete class.
    3. You can use isSubclassOf here, I tend to prefer IsAssignableFrom in general to catch all overridden variants. In particular I think it works with generics.
    4. Take advantage of KnownTypes accepting an IEnumerable (if it matters in this case, probably not) instead of converting to an array.

提交回复
热议问题