4

たとえばEmailAddress、null 以外のインスタンスが有効であることを保証する多くの不変の値型クラスがあります。"123@abc.com"これらのタイプのオブジェクトのシリアル化を、 MongoDB C# ドライバーを使用して永続化するときに標準の文字列表現 ( ) になるように制御したいと考えています。

を実装しようとしIBsonSerilizerましたが、ルート レベルのオブジェクトまたは配列のみが許可されます。Json.NET を使用して適切な Json シリアライゼーションを実装できました。別のアプローチをとるべきですか?

4

3 に答える 3

6

次のような EmailAddress クラスを意味していると思います。

[BsonSerializer(typeof(EmailAddressSerializer))]
public class EmailAddress
{
    private string _value;

    public EmailAddress(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }
}

属性を使用して、EmailAddress クラスを次のように実装できるカスタム シリアライザーにリンクしました。

public class EmailAddressSerializer : BsonBaseSerializer
{
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        if (bsonReader.GetCurrentBsonType() == BsonType.Null)
        {
            bsonReader.ReadNull();
            return null;
        }
        else
        {
            var value = bsonReader.ReadString();
            return new EmailAddress(value);
        }
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        if (value == null)
        {
            bsonWriter.WriteNull();
        }
        else
        {
            var emailAddress = (EmailAddress)value;
            bsonWriter.WriteString(emailAddress.Value);
        }
    }
}

EmailAddress をルート ドキュメントとしてシリアル化することはできません (ドキュメントではないため...)。ただし、他のドキュメントに埋め込まれた EmailAddress を使用できます。例えば:

public class Person
{
    public int Id { get; set; }
    public EmailAddress EmailAddress { get; set; }
}

次のようなコードを使用してテストできます。

var person = new Person { Id = 1, EmailAddress = new EmailAddress("joe@xyz.com") };
var json = person.ToJson();
var rehyrdated = BsonSerializer.Deserialize<Person>(json);

結果の JSON/BSON ドキュメントは次のとおりです。

{ "_id" : 1, "EmailAddress" : "joe@xyz.com" }
于 2013-05-12T00:43:15.727 に答える
2

コンストラクターと一致するコンストラクターに一致するすべての読み取り専用プロパティをマップする規則を作成することにより、この問題を解決しようとしました。

次のようなクラスがあるとします。

public class Person
{
    public string FirstName { get; }
    public string LastName { get; }
    public string FullName => FirstName + LastName;
    public ImmutablePocoSample(string lastName)
    {
        LastName = lastName;
    }

    public ImmutablePocoSample(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

大会のコードは次のとおりです。

/// <summary>
/// A convention that map all read only properties for which a matching constructor is found.
/// Also matching constructors are mapped.
/// </summary>
public class ImmutablePocoConvention : ConventionBase, IClassMapConvention
{
    private readonly BindingFlags _bindingFlags;

    public ImmutablePocoConvention()
            : this(BindingFlags.Instance | BindingFlags.Public)
    { }

    public ImmutablePocoConvention(BindingFlags bindingFlags)
    {
        _bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
    }

    public void Apply(BsonClassMap classMap)
    {
        var readOnlyProperties = classMap.ClassType.GetTypeInfo()
            .GetProperties(_bindingFlags)
            .Where(p => IsReadOnlyProperty(classMap, p))
            .ToList();

        foreach (var constructor in classMap.ClassType.GetConstructors())
        {
            // If we found a matching constructor then we map it and all the readonly properties
            var matchProperties = GetMatchingProperties(constructor, readOnlyProperties);
            if (matchProperties.Any())
            {
                // Map constructor
                classMap.MapConstructor(constructor);

                // Map properties
                foreach (var p in matchProperties)
                    classMap.MapMember(p);
            }
        }
    }

    private static List<PropertyInfo> GetMatchingProperties(ConstructorInfo constructor, List<PropertyInfo> properties)
    {
        var matchProperties = new List<PropertyInfo>();

        var ctorParameters = constructor.GetParameters();
        foreach (var ctorParameter in ctorParameters)
        {
            var matchProperty = properties.FirstOrDefault(p => ParameterMatchProperty(ctorParameter, p));
            if (matchProperty == null)
                return new List<PropertyInfo>();

            matchProperties.Add(matchProperty);
        }

        return matchProperties;
    }


    private static bool ParameterMatchProperty(ParameterInfo parameter, PropertyInfo property)
    {
        return string.Equals(property.Name, parameter.Name, System.StringComparison.InvariantCultureIgnoreCase)
               && parameter.ParameterType == property.PropertyType;
    }

    private static bool IsReadOnlyProperty(BsonClassMap classMap, PropertyInfo propertyInfo)
    {
        // we can't read 
        if (!propertyInfo.CanRead)
            return false;

        // we can write (already handled by the default convention...)
        if (propertyInfo.CanWrite)
            return false;

        // skip indexers
        if (propertyInfo.GetIndexParameters().Length != 0)
            return false;

        // skip overridden properties (they are already included by the base class)
        var getMethodInfo = propertyInfo.GetMethod;
        if (getMethodInfo.IsVirtual && getMethodInfo.GetBaseDefinition().DeclaringType != classMap.ClassType)
            return false;

        return true;
    }
}

次を使用して i を登録できます。

ConventionRegistry.Register(
    nameof(ImmutablePocoConvention),
    new ConventionPack { new ImmutablePocoConvention() },
    _ => true);
于 2016-09-21T10:10:59.330 に答える