How to write custom serializer using DataContractSerializer for generic type?

I want to write my own serializer to store session state in Azure Cache (Preview) , so this means that this custom serializer must implement IDataCacheObjectSerializer (if I am wrong, let me know). The reason I need to write this custome serializer is because I need to serialize some Linq objects that contain some System.Data.Linq.EntitySet attributes. And the default serializer NetDataContractSerializer cannot serialize an EntitySet .

My plan is to write my own serializer using the DataContractSerializer (I searched for some articles that mentioned the DataContractSerializer can serialize an EntitySet , so if I am wrong, please tell me), but the problem is how I can write my own serializer, which can support a generic type.

Currently, my custom serializer codes are similar to:

 public class CustomSerializer : IDataCacheObjectSerializer { public CustomSerializer() { } public object Deserialize(System.IO.Stream stream) { /* How can I know the type of object?????? */ DataContractSerializer dcs = new DataContractSerializer("Type of object"); } public void Serialize(System.IO.Stream stream, object value) { DataContractSerializer dcs = new DataContractSerializer(value.GetType()); dcs.WriteObject(stream, value); } } 

By the way, I changed the Linq Serialization mode to "Unidirectional"

+4
source share
1 answer

I did not work with IDataCacheObjectSerializer, but the general solution looks like this:

 public sealed class CustomSerializer<T> : IDataCacheObjectSerializer { object IDataCacheObjectSerializer.Deserialize(System.IO.Stream stream) { DataContractSerializer dcs = new DataContractSerializer(typeof(T)); return dcs.ReadObject(stream); } void IDataCacheObjectSerializer.Serialize(System.IO.Stream stream, object value) { if (!(value is T)) { throw new AgrumentException(); } DataContractSerializer dcs = new DataContractSerializer(typeof(T)); dcs.WriteObject(stream, value); } } 
+2
source

Source: https://habr.com/ru/post/1437575/


All Articles