从其他assambly添加KnowType的最干净的方法

本文关键字:方法 KnowType 其他 assambly 添加 | 更新日期: 2023-09-27 18:25:58

我有一个基类BaseClass和一个派生的基类DerivedClass。我正在使用以下方法(T=BaseClass)序列化DerivedClass的实例:

    public static string SerializeDataContract<T>(T obj)
    {
        using (var stream = new MemoryStream())
        {
            using (var reader = new StreamReader(stream))
            {
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(stream, obj);
                stream.Position = 0;
                return reader.ReadToEnd();
            }
        }
    }

我得到了以下异常:SerializationException:将任何不静态已知的类型添加到已知类型列表中,例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表。

如何在不更改Serialization方法的情况下序列化DerivedClass的实例?(Remember:DerivedClass在另一个程序集中)

我目前使用以下内容,但我不是一个大粉丝。一些想法?

    //In base class
        [KnownType("GetKnownType")]
        public abstract class GetcReceiverContextBase
        {
            public static event Func<IEnumerable<Type>> KnownTypeRequired;
            private static IEnumerable<Type> GetKnownType()
            {
                var types = new List<Type>();
                if (KnownTypeRequired != null)
                    return KnownTypeRequired();
                return types.ToArray();
            }

//In derived Class
      public class DerivedClass : BaseClass
        {
            static MT514ContextMock()
            {
                KnownTypeRequired += () => new List<Type> { typeof(MT514ContextMock) };
            }

从其他assambly添加KnowType的最干净的方法

来源:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/6b70e9f4-52bc-4fa9-a0ff-c0859e041e85/how-to-configure-serviceknowntype-in-appconfig

以下是文章中的一句话(以防链接失效),但在上面的链接中还有一些额外的讨论。

只需使用[ServiceKnownType("GetKnownTypes",typeof(Helper))]属性,然后让GetKnownType方法从文件中读取AssemblyQualifiedNames并返回类型。

[ServiceKnownType("GetKnownTypes", typeof(Helper))]
public interface MyService
{
    ...
}
static class Helper
{
    public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
    {
        List<Type> knownTypes = new List<System.Type>();
        // Add any types to include here.           
        string[] types = File.ReadAllLines(@"..'..'..'types.txt");
        foreach (string type in types)
        {
            knownTypes.Add(Type.GetType(type));
        }
        return knownTypes;
    }
}

types.txt:NameSpace.MyType,MyAssembly,版本=1.0.0.0,区域性=中性,PublicKeyToken=nullNameSpace.MyOtherType,MyAssembly,版本=1.0.0.0,区域性=中性,PublicKeyToken=空

你也可以看看这里:

如何以编程方式配置WCF已知类型?