/// <summary> /// Add assembly resolution for Microsoft.Build core dlls in the current AppDomain from the specified /// instance of Visual Studio. See <see cref="QueryVisualStudioInstances()" /> to discover Visual Studio /// instances or use <see cref="RegisterDefaults" />. /// </summary> /// <param name="instance"></param> public static void RegisterInstance(VisualStudioInstance instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } RegisterMSBuildPath(instance.MSBuildPath); }
/// <summary> /// Add assembly resolution for Microsoft.Build core dlls in the current AppDomain from the specified /// instance of Visual Studio. See <see cref="QueryVisualStudioInstances()" /> to discover Visual Studio /// instances or use <see cref="RegisterDefaults" />. /// </summary> /// <param name="instance"></param> public static void RegisterInstance(VisualStudioInstance instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (instance.DiscoveryType == DiscoveryType.DotNetSdk) { // The dotnet cli sets up these environment variables when msbuild is invoked via `dotnet`, // but we are using msbuild dlls directly and therefore need to mimic that. ApplyDotNetSdkEnvironmentVariables(instance.MSBuildPath); } RegisterMSBuildPath(instance.MSBuildPath); }
/// <summary> /// Discover instances of Visual Studio and register the first one. See <see cref="RegisterInstance" />. /// </summary> /// <returns>Instance of Visual Studio found and registered.</returns> public static VisualStudioInstance RegisterDefaults() { VisualStudioInstance instance = GetInstances(VisualStudioInstanceQueryOptions.Default).FirstOrDefault(); if (instance == null) { var error = "No instances of MSBuild could be detected." + Environment.NewLine + $"Try calling {nameof(RegisterInstance)} or {nameof(RegisterMSBuildPath)} to manually register one."; throw new InvalidOperationException(error); } RegisterInstance(instance); return(instance); }
/// <summary> /// Add assembly resolution for Microsoft.Build core dlls in the current AppDomain from the specified /// instance of Visual Studio. See <see cref="QueryVisualStudioInstances()" /> to discover Visual Studio /// instances or use <see cref="RegisterDefaults" />. /// </summary> /// <param name="instance"></param> public static void RegisterInstance(VisualStudioInstance instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } AppDomain.CurrentDomain.AssemblyResolve += (_, eventArgs) => { var assemblyName = new AssemblyName(eventArgs.Name); if (s_msBuildAssemblies.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase)) { var targetAssembly = Path.Combine(instance.MSBuildPath, assemblyName.Name + ".dll"); return(File.Exists(targetAssembly) ? Assembly.LoadFrom(targetAssembly) : null); } return(null); }; }