Skip to content

Commit

Permalink
allow the ContractlessStandardResolver to also honor explicitly marke…
Browse files Browse the repository at this point in the history
…d private constructors
  • Loading branch information
pianomanjh committed May 18, 2021
1 parent b652df8 commit db1f36e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

Expand Down Expand Up @@ -48,5 +49,11 @@ public static MethodInfo GetSetMethod(this PropertyInfo propInfo)
{
return propInfo.SetMethod;
}

public static bool HasPrivateCtorForSerialization(this TypeInfo type)
{
var markedCtor = type.DeclaredConstructors.SingleOrDefault(x => x.GetCustomAttribute<SerializationConstructorAttribute>(false) != null);
return markedCtor?.Attributes.HasFlag(MethodAttributes.Private) ?? false;
}
}
}
Expand Up @@ -224,7 +224,7 @@ static FormatterCache()
return;
}

if (ti.IsAnonymous())
if (ti.IsAnonymous() || ti.HasPrivateCtorForSerialization())
{
Formatter = (IMessagePackFormatter<T>)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false);
return;
Expand Down
Expand Up @@ -193,6 +193,25 @@ public ImmutablePrivateClass(int x, int y, bool dummy)
public bool CreatedUsingPrivateCtor { get; }
}

public class ContractlessClassPrivateCtor
{
public int X { get; private set; }

public int Y { get; private set; }

[SerializationConstructor]
private ContractlessClassPrivateCtor(int x, int y)
{
X = x;
Y = y;
}

public static ContractlessClassPrivateCtor Create(int x, int y)
{
return new ContractlessClassPrivateCtor(x, y);
}
}

[MessagePackObject]
public class CompletelyPrivateConstructor
{
Expand Down Expand Up @@ -335,6 +354,17 @@ public void PrivateConstructor2()
Assert.Equal(p1.X, p2.X);
Assert.Equal(p1.Y, p2.Y);
}

[Fact]
public void ContractlessAttributedPrivateConstructor()
{
var p1 = ContractlessClassPrivateCtor.Create(10, 20);
var bin = MessagePackSerializer.Serialize(p1, ContractlessStandardResolver.Options);
var p2 = MessagePackSerializer.Deserialize<ContractlessClassPrivateCtor>(bin, ContractlessStandardResolver.Options);

Assert.Equal(p1.X, p2.X);
Assert.Equal(p1.Y, p2.Y);
}
#endif
}
}
Expand Down

0 comments on commit db1f36e

Please sign in to comment.