Created
May 30, 2018 10:09
-
-
Save pietrom/c0b44136d62d6013473e1957026c7759 to your computer and use it in GitHub Desktop.
Custom mongodb serializer, able to wrap/unwrap string values to/from custom class instances, generic for the type of the (de)serialized custom class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Huxley.MongoDb.Serialization { | |
class StringToObjectSerializer<T> : SerializerBase<T> { | |
private readonly Func<string, T> valueDeserializer; | |
private readonly Func<T, string> valueSerializer; | |
public StringToObjectSerializer(Func<string, T> valueDeserializer, Func<T, string> valueSerializer) { | |
this.valueDeserializer = valueDeserializer; | |
this.valueSerializer = valueSerializer; | |
} | |
public override T Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { | |
string value = context.Reader.ReadString(); | |
return valueDeserializer(value); | |
} | |
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T obj) { | |
context.Writer.WriteString(valueSerializer(obj)); | |
} | |
} | |
} | |
class MyClass { | |
public string Value { get; } | |
public MyClass(string value) { | |
Value = value; | |
} | |
} | |
// Usage: | |
class MyContainer { | |
public MyClass MyProperty { get; private set; } | |
} | |
BsonClassMap.RegisterClassMap<MyContainer>(cm => { | |
cm.MapField(x => x.MyProperty).SetSerializer(new StringToObjectSerializer<MyClass>(s => new MyClass(s), x => x.Value)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment