Skip to content

Commit

Permalink
Merge pull request #1902 from PathogenDavid/issue-1901
Browse files Browse the repository at this point in the history
Fix redundant assembly resolution resulting in duplicate assembly loading
  • Loading branch information
glopesdev authored Jul 13, 2024
2 parents 4adb362 + 9fa8ac5 commit 26f10d4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
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

0 comments on commit 26f10d4

Please sign in to comment.