### Register MSBuild Instance (Latest Version) Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/find-and-use-msbuild-versions?view=vs-2022 This example shows how to register the most recent version of MSBuild found by querying Visual Studio instances. This code should not directly call MSBuild types. ```csharp void ThisWillFail() { // Register the most recent version of MSBuild RegisterInstance(MSBuildLocator.QueryVisualStudioInstances().OrderByDescending( instance => instance.Version).First()); Project p = new Project(SomePath); // Could be any MSBuild type // Code that uses the MSBuild type } ``` -------------------------------- ### Register MSBuild Instance (Specific Instance) Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/find-and-use-msbuild-versions?view=vs-2022 This example demonstrates how to register a specific MSBuild instance after selecting it from the results of MSBuildLocator.QueryVisualStudioInstances. This approach avoids calling MSBuild types directly in the registration method. ```csharp void MethodThatDoesNotDirectlyCallMSBuild() { var instance = ... // select which of the installed instances to use // Register a specific instance of MSBuild MSBuildLocator.RegisterInstance(instance); MethodThatCallsMSBuild(); } void MethodThatCallsMSBuild() { Project p = new Project(SomePath); // Code that uses the MSBuild type } ``` -------------------------------- ### Add NuGet Package Reference for Microsoft.Build.Locator Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/find-and-use-msbuild-versions?view=vs-2022 Add a NuGet package reference for the Microsoft.Build.Locator package to your project. Do not specify ExcludeAssets=runtime for this package. ```xml 1.1.2 ``` -------------------------------- ### Reference MSBuild NuGet Packages Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/find-and-use-msbuild-versions?view=vs-2022 Use this XML in your project file to reference MSBuild assemblies from NuGet packages. Specify `ExcludeAssets=runtime` to ensure assemblies are only used at build time and not copied to the output directory. The version specified should be less than or equal to the minimum Visual Studio version you intend to support. ```XML ``` -------------------------------- ### Reference MSBuild Assemblies with Copy Local False Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/find-and-use-msbuild-versions?view=vs-2022 When referencing MSBuild assemblies directly, set 'Copy Local' to 'False' to prevent them from being copied to the output directory. This is done within the project file. ```xml False ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.