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