In an application I have the following interface / implementation structure:
public interface IMyInterface
{
IMyOtherInterface InstanceOfMyOtherInterface { get; }
}
public interface IMyOtherInterface
{
string SomeValue { get; }
}
[DataContract(Name = "MyInterfaceImplementation", Namespace = "")]
public class MyInterfaceImplementation : IMyInterface
{
[DataMember(EmitDefaultValue = false), XmlAttribute(Namespace = "")]
public IMyOtherInterface InstanceOfMyOtherInterface { get; private set; }
public MyInterfaceImplementation()
{
this.InstanceOfMyOtherInterface = new MyOtherInterfaceImplementation("Hello World");
}
}
[DataContract(Name = "MyOtherInterfaceImplementation", Namespace = "")]
public class MyOtherInterfaceImplementation : IMyOtherInterface
{
[DataMember]
public string SomeValue { get; private set; }
public MyOtherInterfaceImplementation(string value)
{
this.SomeValue = value;
}
}
Now whenever I use a .Net DataContractSerializer to serialize this (in my case into a string) like this:
var dataContractSerializer = new DataContractSerializer(typeof(MyInterfaceImplementation));
var stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(stringBuilder, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }))
{
dataContractSerializer.WriteObject(xmlWriter, this);
}
var stringValue = stringBuilder.ToString();
the resulting xml looks pretty much like this:
<?xml version="1.0" encoding="utf-16"?>
<z:anyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="MyInterfaceImplementation" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<InstanceOfMyOtherInterface xmlns="" i:type="InstanceOfMyOtherInterface">
<SomeValue>Hello World</SomeValue>
</InstanceOfMyOtherInterface>
</z:anyType>
These *anyType*s seem to come from the datacontractserializer's serializing the MyInterfaceImplementation instance as System.Object, likewise with other interface properties.
If I used concrete types in my interface and its implementation(s) like this:
public interface IMyInterface
{
MyOtherInterface InstanceOfMyOtherInterface { get; }
}
.. it works 'fine' as in - the datacontractserializer does create
<MyInterfaceImplementation>...</MyInterfaceImplementation>
...nodes instead of the z:anyType ones but I do not want / can't change my interfaces' properties. Is there any way to control or aid the data contract serializer in such cases?