You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:54:06