FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Update DynamicAssembly usage to honor different AssemblyLoadContext's by BertanAygun · Pull Request #1978 · MessagePack-CSharp/MessagePack-CSharp · GitHub

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

Filter by extension

Filter by extension .cs  (6) .csproj  (1) All 2 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
3 changes: 3 additions & 0 deletions sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj
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
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
<Compile Include="..\..\src\MessagePack\Internal\DynamicAssembly.cs">
<Link>Code\DynamicAssembly.cs</Link>
</Compile>
<Compile Include="..\..\src\MessagePack\Internal\DynamicAssemblyFactory.cs">
<Link>Code\DynamicAssemblyFactory.cs</Link>
</Compile>
<Compile Include="..\..\src\MessagePack\Internal\ExpressionUtility.cs">
<Link>Code\ExpressionUtility.cs</Link>
</Compile>
Expand Down
5 changes: 5 additions & 0 deletions src/MessagePack/Internal/DynamicAssembly.cs
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,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
63 changes: 63 additions & 0 deletions src/MessagePack/Internal/DynamicAssemblyFactory.cs
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
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
}
}
8 changes: 4 additions & 4 deletions src/MessagePack/Resolvers/DynamicEnumResolver.cs
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,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 @@ -33,13 +33,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 @@ -93,7 +93,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
16 changes: 8 additions & 8 deletions src/MessagePack/Resolvers/DynamicObjectResolver.cs
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
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,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 @@ -52,7 +52,7 @@ private DynamicObjectResolver()
#if NETFRAMEWORK
internal AssemblyBuilder Save()
{
return DynamicAssembly.Value.Save();
return DynamicAssemblyFactory.GetDynamicAssembly(type: null).Save();
}
#endif

Expand Down Expand Up @@ -97,7 +97,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 @@ -179,21 +179,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 @@ -240,7 +240,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
8 changes: 4 additions & 4 deletions src/MessagePack/Resolvers/DynamicUnionResolver.cs
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
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ public sealed class DynamicUnionResolver : IFormatterResolver
/// </summary>
public static readonly MessagePackSerializerOptions Options;

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

private static int nameSequence = 0;

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

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

Expand Down Expand Up @@ -131,7 +131,7 @@ static FormatterCache()
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
using (MonoProtection.EnterRefEmitLock())
{
TypeBuilder typeBuilder = DynamicAssembly.Value.DefineType("MessagePack.Formatters." + DynamicObjectTypeBuilder.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." + DynamicObjectTypeBuilder.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
137 changes: 137 additions & 0 deletions tests/MessagePack.Tests/AssemblyLoadContextTests.cs
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if NET

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;
using ComplexdUnion;
using MessagePack;
using MessagePack.Formatters;
using MessagePack.Resolvers;
using SharedData;
using Xunit;

#pragma warning disable SA1302 // Interface names should begin with I
#pragma warning disable SA1403 // File may only contain a single namespace

public class AssemblyLoadContextTests : IDisposable
{
private static readonly string SharedDataAssemblyName = typeof(RootUnionType).Assembly.Location;
private readonly AssemblyLoadContext loadContext = new AssemblyLoadContext("TestContext", isCollectible: true);

public void Dispose()
{
this.loadContext.Unload();
}

[Fact]
public void DynamicUnionResolverWorksAcrossAssemblyLoadContexts()
{
RootUnionType unionTypeInMainLoadContext = new SubUnionType1();
var options = this.CreateSerializerOptions();

var buffer1 = MessagePackSerializer.Serialize(unionTypeInMainLoadContext, options: options);
var o1 = MessagePackSerializer.Deserialize<RootUnionType>(buffer1, options: options);

Assert.True(o1 is SubUnionType1);

var assembly = this.loadContext.LoadFromAssemblyPath(SharedDataAssemblyName);
object unionTypeInOtherContext = assembly.CreateInstance(typeof(SubUnionType1).FullName);
Type rootUnionType = assembly.GetType(typeof(RootUnionType).FullName);

var buffer2 = MessagePackSerializer.Serialize(rootUnionType, unionTypeInOtherContext, options: options);
var o2 = MessagePackSerializer.Deserialize(rootUnionType, buffer2, options: options);

Assert.True(o2.GetType().IsAssignableTo(rootUnionType));
}

[Fact]
public void DynamicEnumResolverWorksAcrossAssemblyLoadContexts()
{
ByteEnum e1 = ByteEnum.A;
var options = this.CreateSerializerOptions();

var b1 = MessagePackSerializer.Serialize(e1, options: options);
var o1 = MessagePackSerializer.Deserialize<ByteEnum>(b1, options: options);

Assert.Equal(typeof(ByteEnum), o1.GetType());

var assembly = this.loadContext.LoadFromAssemblyPath(SharedDataAssemblyName);
Type enumType = assembly.GetType(typeof(ByteEnum).FullName);
object e2 = Enum.GetValues(enumType).GetValue(1);

var b2 = MessagePackSerializer.Serialize(enumType, e2, options: options);
var o2 = MessagePackSerializer.Deserialize(enumType, b2, options: options);

Assert.Equal(o2.GetType(), e2.GetType());
}

[Fact]
public void DynamicObjectResolverWorksAcrossAssemblyLoadContexts()
{
FirstSimpleData e1 = new FirstSimpleData();
var options = this.CreateSerializerOptions();

var b1 = MessagePackSerializer.Serialize(e1, options: options);
var o1 = MessagePackSerializer.Deserialize<FirstSimpleData>(b1, options: options);

Assert.Equal(typeof(FirstSimpleData), o1.GetType());

var assembly = this.loadContext.LoadFromAssemblyPath(SharedDataAssemblyName);
Type objectType = assembly.GetType(typeof(FirstSimpleData).FullName);
object e2 = assembly.CreateInstance(typeof(FirstSimpleData).FullName);

var b2 = MessagePackSerializer.Serialize(objectType, e2, options: options);
var o2 = MessagePackSerializer.Deserialize(objectType, b2, options: options);

Assert.Equal(o2.GetType(), e2.GetType());
}

[Fact]
public void DynamicContractlessObjectResolverWorksAcrossAssemblyLoadContexts()
{
FirstSimpleData e1 = new FirstSimpleData();
var options = new MessagePackSerializerOptions(
CompositeResolver.Create(
BuiltinResolver.Instance,
PrimitiveObjectResolver.Instance,
DynamicContractlessObjectResolver.Instance));

var b1 = MessagePackSerializer.Serialize(e1, options: options);
var o1 = MessagePackSerializer.Deserialize<FirstSimpleData>(b1, options: options);

Assert.Equal(typeof(FirstSimpleData), o1.GetType());

var assembly = this.loadContext.LoadFromAssemblyPath(SharedDataAssemblyName);
Type objectType = assembly.GetType(typeof(FirstSimpleData).FullName);
object e2 = assembly.CreateInstance(typeof(FirstSimpleData).FullName);

var b2 = MessagePackSerializer.Serialize(objectType, e2, options: options);
var o2 = MessagePackSerializer.Deserialize(objectType, b2, options: options);

Assert.Equal(o2.GetType(), e2.GetType());
}

private MessagePackSerializerOptions CreateSerializerOptions()
{
// Avoid default options as it will use source generated formatter which works in this scenario.
return new MessagePackSerializerOptions(
CompositeResolver.Create(
BuiltinResolver.Instance,
AttributeFormatterResolver.Instance,
DynamicEnumResolver.Instance,
DynamicGenericResolver.Instance,
DynamicUnionResolver.Instance,
DynamicObjectResolver.Instance,
PrimitiveObjectResolver.Instance));
}
}

#endif

Back | FazBrowse Home | New Git URL