Visitar URL original
Update DynamicAssembly usage to honor different AssemblyLoadContext's by BertanAygun · Pull Request #2183 · MessagePack-CSharp/MessagePack-CSharp · GitHub
Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@
<Compile Include="..\..\src\MessagePack.UnityClient\Assets\Scripts\MessagePack\Internal\DynamicAssembly.cs">
<Link>Code\DynamicAssembly.cs</Link>
</Compile>
<Compile Include="..\..\src\MessagePack.UnityClient\Assets\Scripts\MessagePack\Internal\DynamicAssemblyFactory.cs">
<Link>Code\DynamicAssemblyFactory.cs</Link>
</Compile>
<Compile Include="..\..\src\MessagePack.UnityClient\Assets\Scripts\MessagePack\Internal\ExpressionUtility.cs">
<Link>Code\ExpressionUtility.cs</Link>
</Compile>
Expand Down
47 changes: 47 additions & 0 deletions sandbox/Sandbox/Generated.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3093,6 +3093,53 @@ public void Serialize(ref global::MessagePack.MessagePackWriter writer, global::
}
}

public sealed class SimpleGenericDataFormatter<T> : global::MessagePack.Formatters.IMessagePackFormatter<global::SharedData.SimpleGenericData<T>>
{

public void Serialize(ref global::MessagePack.MessagePackWriter writer, global::SharedData.SimpleGenericData<T> value, global::MessagePack.MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}

global::MessagePack.IFormatterResolver formatterResolver = options.Resolver;
writer.WriteArrayHeader(1);
global::MessagePack.FormatterResolverExtensions.GetFormatterWithVerify<T>(formatterResolver).Serialize(ref writer, value.Value, options);
}

public global::SharedData.SimpleGenericData<T> Deserialize(ref global::MessagePack.MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return null;
}

options.Security.DepthStep(ref reader);
global::MessagePack.IFormatterResolver formatterResolver = options.Resolver;
var length = reader.ReadArrayHeader();
var __Value__ = default(T);

for (int i = 0; i < length; i++)
{
switch (i)
{
case 0:
__Value__ = global::MessagePack.FormatterResolverExtensions.GetFormatterWithVerify<T>(formatterResolver).Deserialize(ref reader, options);
break;
default:
reader.Skip();
break;
}
}

var ____result = new global::SharedData.SimpleGenericData<T>(__Value__);
reader.Depth--;
return ____result;
}
}

public sealed class SimpleIntKeyDataFormatter : global::MessagePack.Formatters.IMessagePackFormatter<global::SharedData.SimpleIntKeyData>
{

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ internal class DynamicAssembly
// don't expose ModuleBuilder
//// public ModuleBuilder ModuleBuilder { get { return moduleBuilder; } }

/// <summary>
/// Initializes a new instance of the <see cref="DynamicAssembly"/> class.
/// Please use <see cref="DynamicAssemblyFactory"/> instead in order to work across different AssemblyLoadContext that may have duplicate modules.
/// </summary>
/// <param name="moduleName">Name of the module to be generated.</param>
public DynamicAssembly(string moduleName)
{
#if NETFRAMEWORK // We don't ship a net472 target, but we might add one for debugging purposes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Reflection;

#if NET
using System.Runtime.Loader;
#endif

namespace MessagePack.Internal
{
/// <summary>
/// This class is responsible for managing DynamicAssembly instance creation taking into account
/// AssemblyLoadContext when running under .NET.
/// </summary>
internal class DynamicAssemblyFactory
{
private readonly string moduleName;

private readonly Lazy<DynamicAssembly> singletonAssembly;

#if NET
private readonly Dictionary<AssemblyLoadContext, DynamicAssembly> alcCache = new();
#endif

public DynamicAssemblyFactory(string moduleName)
{
this.moduleName = moduleName;
this.singletonAssembly = new Lazy<DynamicAssembly>(() => new DynamicAssembly(this.moduleName));
}

#if NET
public DynamicAssembly GetDynamicAssembly(Type? type)
{
if (type is null || AssemblyLoadContext.GetLoadContext(type.Assembly) is not AssemblyLoadContext loadContext)
{
return this.singletonAssembly.Value;
}
else
{
DynamicAssembly? assembly = null;
lock (this.alcCache)
{
if (!this.alcCache.TryGetValue(loadContext, out assembly))
{
assembly = new DynamicAssembly(this.moduleName);
this.alcCache[loadContext] = assembly;
}

return assembly;
}
}
}
#else
public DynamicAssembly GetDynamicAssembly(Type? type)
{
return this.singletonAssembly.Value;
}
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public sealed class DynamicEnumResolver : IFormatterResolver

private const string ModuleName = "MessagePack.Resolvers.DynamicEnumResolver";

private static readonly Lazy<DynamicAssembly> DynamicAssembly;
private static readonly DynamicAssemblyFactory DynamicAssemblyFactory;

private static int nameSequence = 0;

Expand All @@ -35,13 +35,13 @@ private DynamicEnumResolver()

static DynamicEnumResolver()
{
DynamicAssembly = new Lazy<DynamicAssembly>(() => new DynamicAssembly(ModuleName));
DynamicAssemblyFactory = new DynamicAssemblyFactory(ModuleName);
}

#if NETFRAMEWORK
internal AssemblyBuilder Save()
{
return DynamicAssembly.Value.Save();
return DynamicAssemblyFactory.GetDynamicAssembly(type: null).Save();
}
#endif

Expand Down Expand Up @@ -95,7 +95,7 @@ private static TypeInfo BuildType(Type enumType)
{
using (MonoProtection.EnterRefEmitLock())
{
TypeBuilder typeBuilder = DynamicAssembly.Value.DefineType("MessagePack.Formatters." + enumType.FullName!.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });
TypeBuilder typeBuilder = DynamicAssemblyFactory.GetDynamicAssembly(enumType).DefineType("MessagePack.Formatters." + enumType.FullName!.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });

// void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options);
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ public sealed class DynamicObjectResolver : IFormatterResolver
/// </summary>
public static readonly MessagePackSerializerOptions Options;

internal static readonly Lazy<DynamicAssembly> DynamicAssembly;
internal static readonly DynamicAssemblyFactory DynamicAssemblyFactory;

static DynamicObjectResolver()
{
Instance = new DynamicObjectResolver();
Options = new MessagePackSerializerOptions(Instance);
DynamicAssembly = new Lazy<DynamicAssembly>(() => new DynamicAssembly(ModuleName));
DynamicAssemblyFactory = new DynamicAssemblyFactory(ModuleName);
}

private DynamicObjectResolver()
Expand All @@ -54,7 +54,7 @@ private DynamicObjectResolver()
#if NETFRAMEWORK
internal AssemblyBuilder Save()
{
return DynamicAssembly.Value.Save();
return DynamicAssemblyFactory.GetDynamicAssembly(type: null).Save();
}
#endif

Expand Down Expand Up @@ -99,7 +99,7 @@ static FormatterCache()
TypeInfo? formatterTypeInfo;
try
{
formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), false, false);
formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssemblyFactory.GetDynamicAssembly(typeof(T)), typeof(T), false, false);
}
catch (InitAccessorInGenericClassNotSupportedException)
{
Expand Down Expand Up @@ -181,21 +181,21 @@ public sealed class DynamicContractlessObjectResolver : IFormatterResolver

private const string ModuleName = "MessagePack.Resolvers.DynamicContractlessObjectResolver";

private static readonly Lazy<DynamicAssembly> DynamicAssembly;
private static readonly DynamicAssemblyFactory DynamicAssemblyFactory;

private DynamicContractlessObjectResolver()
{
}

static DynamicContractlessObjectResolver()
{
DynamicAssembly = new Lazy<DynamicAssembly>(() => new DynamicAssembly(ModuleName));
DynamicAssemblyFactory = new DynamicAssemblyFactory(ModuleName);
}

#if NETFRAMEWORK
internal AssemblyBuilder Save()
{
return DynamicAssembly.Value.Save();
return DynamicAssemblyFactory.GetDynamicAssembly(type: null).Save();
}
#endif

Expand Down Expand Up @@ -242,7 +242,7 @@ static FormatterCache()
return;
}

TypeInfo? formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), true, true);
TypeInfo? formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssemblyFactory.GetDynamicAssembly(typeof(T)), typeof(T), true, true);
if (formatterTypeInfo == null)
{
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ public sealed class DynamicUnionResolver : IFormatterResolver
/// </summary>
public static readonly MessagePackSerializerOptions Options;

private static readonly Lazy<DynamicAssembly> DynamicAssembly;
private static readonly DynamicAssemblyFactory DynamicAssemblyFactory;

#if !UNITY_2018_3_OR_NEWER
private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled);
#else
Expand All @@ -50,7 +51,7 @@ static DynamicUnionResolver()
{
Instance = new DynamicUnionResolver();
Options = new MessagePackSerializerOptions(Instance);
DynamicAssembly = new Lazy<DynamicAssembly>(() => new DynamicAssembly(ModuleName));
DynamicAssemblyFactory = new DynamicAssemblyFactory(ModuleName);
}

private DynamicUnionResolver()
Expand All @@ -60,7 +61,7 @@ private DynamicUnionResolver()
#if NETFRAMEWORK
internal AssemblyBuilder Save()
{
return DynamicAssembly.Value.Save();
return DynamicAssemblyFactory.GetDynamicAssembly(type: null).Save();
}
#endif

Expand Down Expand Up @@ -138,7 +139,7 @@ static FormatterCache()
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
using (MonoProtection.EnterRefEmitLock())
{
TypeBuilder typeBuilder = DynamicAssembly.Value.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName!, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });
TypeBuilder typeBuilder = DynamicAssemblyFactory.GetDynamicAssembly(type).DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName!, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });

FieldBuilder? typeToKeyAndJumpMap = null; // Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>
FieldBuilder? keyToJumpMap = null; // Dictionary<int, int>
Expand Down
12 changes: 12 additions & 0 deletions src/MessagePack.UnityClient/Assets/Scripts/Tests/Class1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ public class SimpleIntKeyData
////public int Prop7 { get; set; }
}

[MessagePackObject]
public class SimpleGenericData<T>
{
[Key(0)]
public T Value { get; set; }

public SimpleGenericData(T value)
{
this.Value = value;
}
}

public class OreOreFormatter : IMessagePackFormatter<int>
{
public int Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
Expand Down
Loading