I'm tinkering around with WCF and MemoryCache. The goal is to host WCF in a Windows Service so different clients can access this cache.
The first part, setting up the host works fine and I'm able to write to and read from the cache via a separate client application. At least, when trying to put very simple objects in the cache, like a string or a value type like int.
When I try a 'custom' object, even if it only has a string property, stuff starts to go wrong:
There was an error while trying to serialize parameter http://tempuri.org/:value.
TheInnerException message was 'Type 'Solution.MyType' with data contract name
'MyType:http://schemas.datacontract.org/2004/07/MyType' is not expected.
Consider using a DataContractResolver or 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.'.
Please see InnerException for more details.
Now after some searching I found that I might had to decorate my type with a KnownType attribute, but alas, with no succes. I also tried decorating it with DataContract and DataMember attributes, but no sigar either.
What to do now? Isn't the WCF DataContractResolver supposed to do this work for me? I find it hard to believe I'd have to write a custom DataContractResolver for every class I want to have serialized. What else are the DataContract and DataMember attributes for?
What am I missing here? Note also that MyType does not inherit from another class (save object).
I've solved this by implementing some custom serialisation:
string result = string.Empty;
Encoding encoding = Encoding.UTF8;
DataContractSerializer ser = new DataContractSerializer(typeof(MyType));
MemoryStream stream = new MemoryStream();
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, encoding, true))
{
ser.WriteObject(writer, principal);
writer.Flush();
result = encoding.GetString(stream.ToArray());
}
which suffices for my purposes.