Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow private constructors for the ContractlessStandardResolver, when using ctor attribute #1241

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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