问题描述:

I have a base class BaseClass and a derived one DerivedClass in two dinstinct assembly. I am serializing an instance of DerivedClass with the following method (T=BaseClass) :

 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();

}

}

}

I got the following exception: SerializationException : Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

How can I serialize an instance of DerivedClass without changing the Serialization method ? (Remeber : DerivedClass is in an other assembly)

I currently use the following, but I am not a big fan. Some ideas ?

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

}

网友答案:

From:

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

Below is a quote from the post (in case the link dies), but there is some extra discussion at the link above.

Just use the [ServiceKnownType("GetKnownTypes", typeof(Helper))] attribute and then have the GetKnownTypes method read AssemblyQualifiedNames from a file and return the types.

[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, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null NameSpace.MyOtherType, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

You can also look here:

How do you configure WCF known types programmatically?

相关阅读:
Top