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

Ensure all resolved assemblies are unique #1904

Merged
merged 1 commit into from
Jul 13, 2024
Merged
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
44 changes: 21 additions & 23 deletions Bonsai.Configuration/ConfigurationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -126,45 +127,42 @@ public static void SetAssemblyResolve(PackageConfiguration configuration, bool a
AddLibraryPath(path);
}

Dictionary<string, Assembly> assemblyLoadCache = null;
ResolveEventHandler assemblyResolveHandler = (sender, args) =>
ConcurrentDictionary<string, Assembly> resolveCache = new();
AppDomain.CurrentDomain.AssemblyResolve += (_, args) =>
{
var assemblyName = new AssemblyName(args.Name).Name;
if (resolveCache.TryGetValue(assemblyName, out var assembly))
return assembly;

var assemblyLocation = GetAssemblyLocation(configuration, assemblyName);
if (assemblyLocation != null)
{
if (assemblyLocation.StartsWith(Uri.UriSchemeFile) && Uri.TryCreate(assemblyLocation, UriKind.Absolute, out Uri uri))
{
assemblyLoadCache ??= new Dictionary<string, Assembly>();
if (!assemblyLoadCache.TryGetValue(uri.LocalPath, out Assembly assembly))
{
var assemblyBytes = File.ReadAllBytes(uri.LocalPath);
assembly = Assembly.Load(assemblyBytes);
assemblyLoadCache.Add(uri.LocalPath, assembly);
}
return assembly;
var assemblyBytes = File.ReadAllBytes(uri.LocalPath);
assembly = Assembly.Load(assemblyBytes);
}

if (!Path.IsPathRooted(assemblyLocation))
else
{
assemblyLocation = Path.Combine(configurationRoot, assemblyLocation);
}
if (!Path.IsPathRooted(assemblyLocation))
{
assemblyLocation = Path.Combine(configurationRoot, assemblyLocation);
}

if (File.Exists(assemblyLocation))
{
if (!assemblyLock)
if (File.Exists(assemblyLocation))
{
var assemblyBytes = File.ReadAllBytes(assemblyLocation);
return Assembly.Load(assemblyBytes);
if (!assemblyLock)
{
var assemblyBytes = File.ReadAllBytes(assemblyLocation);
assembly = Assembly.Load(assemblyBytes);
}
else assembly = Assembly.LoadFrom(assemblyLocation);
}
else return Assembly.LoadFrom(assemblyLocation);
}
}

return null;
return resolveCache.GetOrAdd(assemblyName, assembly);
};

AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveHandler;
}

public static void SetAssemblyResolve()
Expand Down