Last active
August 29, 2023 00:13
-
-
Save ruxo/f60142fa72fd39acc6aaf3c66d79cab7 to your computer and use it in GitHub Desktop.
LanguageExt's Seq<T> serializer for Mongo DB
This file contains hidden or 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
using MongoDB.Bson; | |
using MongoDB.Bson.Serialization; | |
using MongoDB.Bson.Serialization.Conventions; | |
using MongoDB.Bson.Serialization.Serializers; | |
using LanguageExt; | |
public class SeqSerializationProvider : IBsonSerializationProvider | |
{ | |
public IBsonSerializer? GetSerializer(Type type) | |
{ | |
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Seq<>)) return null; | |
var valueType = type.GetGenericArguments()[0]; | |
var serializerType = typeof(SeqSerializer<>).MakeGenericType(valueType); | |
return (IBsonSerializer?)Activator.CreateInstance(serializerType); | |
} | |
} | |
public class SeqSerializer<T> : SerializerBase<Seq<T>> | |
{ | |
readonly ArraySerializer<T> serializer = new(); | |
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Seq<T> value) | |
{ | |
serializer.Serialize(context, args, value.ToArray()); | |
} | |
public override Seq<T> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) => | |
serializer.Deserialize(context, args).ToSeq(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment