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

Error if msbuild already loaded #14

Merged
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
27 changes: 26 additions & 1 deletion src/MSBuildLocator/MSBuildLocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,25 @@ public static void RegisterInstance(VisualStudioInstance instance)
if (instance == null)
throw new ArgumentNullException(nameof(instance));

var loadedMSBuildAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(IsMSBuildAssembly);
if (loadedMSBuildAssemblies.Any())
{
var loadedAssemblyList = string.Join(Environment.NewLine, loadedMSBuildAssemblies.Select(a => a.GetName()));

var error = $"{typeof(MSBuildLocator)}.{nameof(RegisterInstance)} was called, but MSBuild assemblies were already loaded." +
Environment.NewLine +
$"Ensure that {nameof(RegisterInstance)} is called before any method that directly references types in the Microsoft.Build namespace has been called." +
Environment.NewLine +
"Loaded MSBuild assemblies: " +
loadedAssemblyList;

throw new InvalidOperationException(error);
}

AppDomain.CurrentDomain.AssemblyResolve += (_, eventArgs) =>
{
var assemblyName = new AssemblyName(eventArgs.Name);
if (s_msBuildAssemblies.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase))
if (IsMSBuildAssembly(assemblyName))
{
var targetAssembly = Path.Combine(instance.MSBuildPath, assemblyName.Name + ".dll");
return File.Exists(targetAssembly) ? Assembly.LoadFrom(targetAssembly) : null;
Expand All @@ -79,6 +94,16 @@ public static void RegisterInstance(VisualStudioInstance instance)
};
}

private static bool IsMSBuildAssembly(Assembly assembly)
{
return IsMSBuildAssembly(assembly.GetName());
}

private static bool IsMSBuildAssembly(AssemblyName assemblyName)
{
return s_msBuildAssemblies.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase);
}

private static IEnumerable<VisualStudioInstance> GetInstances()
{
var devConsole = GetDevConsoleInstance();
Expand Down