当 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
或 dotnet build
的命令行生成,不适用于 Visual Studio 内部的生成。 因此,最好不要将自定义放在解决方案级别。 自定义解决方案中所有项目的更好的替代方法是使用解决方案文件夹中的 Directory.Build.props 和 Directory.Build.targets 文件。
要将数据写入$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile
文件夹,通常需要管理员权限。 如果有许多解决方案文件以相同的方式进行扩展,但不想写入 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.targets 文件来设置属性 ImportDirectorySolutionProps
和 ImportDirectorySolutionTargets
为 false
。
或者,可以使用 $(DirectorySolutionPropsPath)
和 $(DirectorySolutionTargetsPath)
属性为这些文件指定不同的位置。 如果解决方案的子集需要某些属性值或目标,则此方法非常有用。
注释
在 MSBuild 17.12 及更高版本中,.slnx
解决方案文件格式支持解决方案生成。
before.<solutionname.slnx.targets>和before.<solutionname>.sln.targets,以及相应的after文件,都可以使用 MSBuild 17.14 及更高版本。
有关生成自定义选项的详细信息,请参阅 “自定义生成”。