In Assembly A:
[DataContract]
public class Base
{
[DataMember]
public string SomeText { get; set; }
}
In Assembly B:
internal class Helper
{
internal static Base Deserialize(string serializedInstanceOfTypeBase)
{
DataContractSerializer serializer = new DataContractSerializer(typeof (Base));
XmlReader reader = XmlReader.Create(new StringReader(serializedInstanceOfTypeBase));
return (Base)serializer.ReadObject(reader);
}
}
In Assembly C:
[DataContract]
public class Derived : Base
{
[DataMember]
public string SomeMoreText { get; set; }
}
If I serialize an instance of type Derived
and pass it to Helper.Deserialize()
method, it fails with the SerializationException
:
Error in line 1 position 2. Expecting element 'Base' from namespace 'http://schemas.datacontract.org/2004/07'.. Encountered 'Element' with name 'Derived', namespace 'http://schemas.datacontract.org/2004/07'.
How can I get rid of this issue?
I am aware of the KnownType
attribute, but at the time of coding in assembly A and B, I am absolutely not aware of its derived types. So I cannot use that solution.
Design of my product is more complex which I cannot post here entirely. Helper.Desrialize()
method just gets a string
argument. There is no way (at present at least) for assembly A or B, to know about derived types of Base
class, even at runtime.
Assembly B references assembly A. But A & B cannot reference assembly C.
I am using C# 4.0. It's ok if the solution you provide is NOT using DataContractSerializer
.
SerializedObject
which would contain full type information (assembly name, full class name), along with its serialized XML string. My data transfer layer would strongly type itself againstSerializedObject
, grab a runtime reference to the type (say viaType.GetType
), then deserialize the XML data accordingly via an XmlSerializer. – Ellington