Skip to content
Open
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
32 changes: 6 additions & 26 deletions src/MSBuildLocator/DotNetSdkLocationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,8 @@ internal static partial class DotNetSdkLocationHelper

public static IEnumerable<VisualStudioInstance> GetInstances(string workingDirectory, bool allowQueryAllRuntimes, bool allowAllDotnetLocations)
{
string? bestSdkPath;
string[] allAvailableSdks;
try
{
AddUnmanagedDllResolver();

bestSdkPath = GetSdkFromGlobalSettings(workingDirectory);
allAvailableSdks = GetAllAvailableSDKs(allowAllDotnetLocations).ToArray();
}
finally
{
RemoveUnmanagedDllResolver();
}
string? bestSdkPath = GetSdkFromGlobalSettings(workingDirectory);
string[] allAvailableSdks = GetAllAvailableSDKs(allowAllDotnetLocations).ToArray();

Dictionary<Version, VisualStudioInstance?> versionInstanceMap = new();
foreach (var basePath in allAvailableSdks)
Expand Down Expand Up @@ -169,25 +158,16 @@ static IEnumerable<string> GetAllAvailableSDKs(bool allowAllDotnetLocations)
: resolvedSdk;
}
}

private static void AddUnmanagedDllResolver() => ModifyUnmanagedDllResolver(loadContext => loadContext.ResolvingUnmanagedDll += HostFxrResolver);

private static void RemoveUnmanagedDllResolver() => ModifyUnmanagedDllResolver(loadContext => loadContext.ResolvingUnmanagedDll -= HostFxrResolver);

private static void ModifyUnmanagedDllResolver(Action<AssemblyLoadContext> resolverAction)
static DotNetSdkLocationHelper()
{
// For Windows hostfxr is loaded in the process.
if (!OperatingSystem.IsWindows())
{
var loadContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly());
if (loadContext != null)
{
resolverAction(loadContext);
}
NativeLibrary.SetDllImportResolver(typeof(NativeMethods).Assembly, HostFxrResolver);
}
}

private static IntPtr HostFxrResolver(Assembly assembly, string libraryName)
private static IntPtr HostFxrResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
// the DllImport hardcoded the name as hostfxr.
if (!libraryName.Equals(NativeMethods.HostFxrName, StringComparison.Ordinal))
Expand All @@ -214,7 +194,7 @@ private static IntPtr HostFxrResolver(Assembly assembly, string libraryName)
ShouldIncludePredicate = static (ref FileSystemEntry entry) => entry.IsDirectory
};

var orderedVersions = fileEnumerable.Where(v => v != null).Select(v => v!).OrderByDescending(f => f).ToList();
var orderedVersions = fileEnumerable.Where(v => v != null).Select(v => v!).OrderDescending().ToList();

foreach (SemanticVersion hostFxrVersion in orderedVersions)
{
Expand Down