自定义解决方案生成

当 MSBuild 生成解决方案文件时,它首先在内部转换为项目文件,然后再生成它。 已生成的项目文件在定义任何目标前导入 before.{solutionname}.sln.targets,在导入目标后导入 after.{solutionname}.sln.targets ,其中包括安装到 $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter 目录的目标。

例如,可以在包含以下内容的名为 after.MyCustomizedSolution.sln.targets 的相同目录中创建文件,从而定义在生成 MyCustomizedSolution.sln 后写自定义日志消息的新目标

<Project>
 <Target Name="EmitCustomMessage" AfterTargets="Build">
   <Message Importance="High" Text="The solution has completed the Build target" />
 </Target>
</Project>

解决方案生成与项目生成分开进行,因此,此处的设置不会影响项目生成。

重要

以这种方式自定义解决方案生成将仅适用于带有 MSBuild.exe 的命令行生成。 它不适用于 Visual Studio 中的生成。 出于此原因,不建议将自定义项置于解决方案级别。 自定义一个解决方案中所有项目的更好方法是在解决方案文件夹中使用 Directory.Build.props 和 Directory.build.targets 文件,如本文其他部分所述。

如果有多个要以相同方式扩展的解决方案文件,但不想写入 $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ 文件夹(通常需要提升权限),则可以创建 Directory.Solution.props 和 Directory.Solution.targets 文件,并将其放置在要扩展的解决方案文件的根路径上方。 Directory.Solution.props 在解决方案生成开始时导入,Directory.Solution.targets 在解决方案生成结束时导入。 生成解决方案文件时,不会导入 Directory.Build.props 和 Directory.Build.targets,因此必须使用 Directory.Solution.props 和 Directory.Solution.targets。 它们不会隐式相互导入。

如果根文件夹中有 Directory.Solution.props 或 Directory.Solution.targets,但在该文件夹下有一个不想导入它们的解决方案,则可以使用前面提到的特定于解决方案的文件 before.{solutionname}.sln.targetsafter.{solutionname}.sln.targets 将属性 $(ImportDirectorySolutionProps)$(ImportDirectorySolutionTargets) 设置为 false。 或者,可以使用属性 $(DirectorySolutionPropsPath)$(DirectorySolutionTargetsPath) 为这些文件指定不同的位置。 如果你的各种解决方案子集需要某些属性值或子集通用的目标,这可能很有用。