如何让.nuget中BeforeBuild绑定的Target在多项目解决方案下仅执行一次
自定义MSBuild Target单次执行解决方案
你可以通过全局属性标记的方式,让Target在单次构建会话中仅执行一次,修改你的nuget.targets文件中的Target定义即可:
<Target Name="CustomClearTenantPackage" BeforeTargets="Build" Condition="'$(RanCustomClearTenantTarget)' == ''"> <Message Text="custom clear!!!" Importance="High" /> <ItemGroup> <_tenant Include="$(PackagesDir)\Tenant.1.1.0\**\*" /> </ItemGroup> <Delete Files="@(_tenant)" /> <RemoveDir Directories="$(PackagesDir)\Tenant.1.1.0\" /> <!-- 执行完成后设置全局标记,后续项目导入该Target时会跳过执行 --> <PropertyGroup> <RanCustomClearTenantTarget>true</RanCustomClearTenantTarget> </PropertyGroup> </Target>
- 核心逻辑是通过
Condition判断全局标记属性是否存在,首次执行后将标记属性设为true,同个构建会话下所有后续项目的该Target都会因条件不满足跳过 - 你可以根据实际需求调整
BeforeTargets的取值,比如需要在清理阶段执行就改为BeforeTargets="Clean",需要在生成后执行改为AfterTargets="Build" - 如果你的构建场景开启了多进程并行构建(
msbuild /m参数),属性可能存在跨进程不共享的问题,可以替换为文件标记方案:
<Target Name="CustomClearTenantPackage" BeforeTargets="Build" Condition="!Exists('$(IntermediateOutputPath)\custom_clear_complete.flag')"> <Message Text="custom clear!!!" Importance="High" /> <ItemGroup> <_tenant Include="$(PackagesDir)\Tenant.1.1.0\**\*" /> </ItemGroup> <Delete Files="@(_tenant)" /> <RemoveDir Directories="$(PackagesDir)\Tenant.1.1.0\" /> <!-- 创建标记文件,后续执行判断文件存在就跳过 --> <Touch Files="$(IntermediateOutputPath)\custom_clear_complete.flag" AlwaysCreate="true" /> <!-- 注册构建结束后删除标记文件的逻辑,避免下次构建被拦截 --> <ItemGroup> <FileWrites Include="$(IntermediateOutputPath)\custom_clear_complete.flag" /> </ItemGroup> </Target>
内容的提问来源于stack exchange,提问作者parru pooja
相关产品推荐
相关产品推荐

