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

Fix redundant assembly resolution resulting in duplicate assembly loading #1902

Merged
merged 1 commit into from
Jul 13, 2024
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
1 change: 1 addition & 0 deletions Bonsai/Bonsai.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
</_IlRepackCommand>
</PropertyGroup>
<Exec WorkingDirectory="$(RepackedOutputPath)" Command="$(_IlRepackCommand.Replace('%0D', ' ').Replace('%0A', ' '))" UseCommandProcessor="false" />
<Copy SourceFiles="$(TargetDir)NuGet.config" DestinationFolder="$(RepackedOutputPath)" />
</Target>

<Target Name="UseRepackOutputForPackage" Condition="'$(UseRepackForBootstrapperPackage)' == 'true'" AfterTargets="BuiltProjectOutputGroup" DependsOnTargets="ConfigureRepack">
Expand Down
13 changes: 11 additions & 2 deletions Bonsai/SystemResourcesExtensionsSupport.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;

Expand All @@ -16,19 +17,27 @@ internal static class SystemResourcesExtensionsSupport
[Conditional("NETFRAMEWORK")]
internal static void Initialize()
{
// Assembly.Load(byte[]) always results in a new assembly so we need to manually de-duplicate them
ConcurrentDictionary<string, Assembly> resolveCache = new();

AppDomain.CurrentDomain.AssemblyResolve += (_, args) =>
{
var assemblyName = new AssemblyName(args.Name);

if (resolveCache.TryGetValue(assemblyName.Name, out var cachedResult))
return cachedResult;

using var embeddedAssembly = typeof(SystemResourcesExtensionsSupport).Assembly.GetManifestResourceStream($"{nameof(Bonsai)}.{assemblyName.Name}.dll");

if (embeddedAssembly is null)
return null;
return resolveCache.GetOrAdd(assemblyName.Name, (Assembly)null);

var assemblyBytes = new byte[embeddedAssembly.Length];
int readLength = embeddedAssembly.Read(assemblyBytes, 0, assemblyBytes.Length);
Debug.Assert(readLength == assemblyBytes.Length);

var result = Assembly.Load(assemblyBytes);
result = resolveCache.GetOrAdd(assemblyName.Name, result);
Debug.WriteLine($"Redirecting '{args.Name}' to embedded '{result.FullName}'");
return result;
};
Expand Down