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

如何通过项目引用测试含传递NuGet依赖的.NET源代码生成器

.NET源代码生成器集成测试依赖解析问题解决方案

问题概述

我有一个引用NuGet包的.NET源代码生成器项目,创建集成测试项目通过项目引用关联生成器后,构建时出现CS8032错误:无法加载CommonLibrary程序集。生成器打包为NuGet包引用时正常工作,但不想每次修改代码都推送新NuGet包,尝试过复制DLL、直接引用包/项目等方法均无效。

可行解决方案

方案1:修改生成器项目,自动复制依赖并传递给测试项目

修改SourceGenerator.csproj,添加目标逻辑,在构建时将依赖的CommonLibrary.dll复制到生成器输出目录,并在项目引用时将其标记为分析器资源:

<Project Sdk="Microsoft.NET.Sdk">
    <!-- 原有配置保持不变 -->

    <!-- 新增:针对项目引用场景复制依赖到输出目录 -->
    <Target Name="CopyGeneratorDependencies" AfterTargets="Build">
        <ItemGroup>
            <GeneratorDependencies Include="@(ResolvedCompileFileDefinitions)" 
                                   Condition="%(NuGetPackageId) == 'CommonLibrary'" />
        </ItemGroup>
        <Copy SourceFiles="@(GeneratorDependencies)" DestinationFolder="$(OutputPath)" />
    </Target>

    <!-- 新增:被项目引用时,将依赖也标记为Analyzer输出 -->
    <Target Name="AddDependenciesAsAnalyzers" BeforeTargets="GetCopyToOutputDirectoryItems">
        <ItemGroup>
            <Analyzer Include="@(GeneratorDependencies)" Condition="'$(MSBuildProjectExtension)' == '.csproj' And '@(GeneratorDependencies)' != ''" />
        </ItemGroup>
    </Target>
</Project>

同时更新测试项目的ProjectReference配置:

<ItemGroup>
    <ProjectReference Include="../SourceGenerator/SourceGenerator.csproj">
        <OutputItemType>Analyzer</OutputItemType>
        <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
        <PrivateAssets>all</PrivateAssets>
    </ProjectReference>
</ItemGroup>

方案2:将生成器对CommonLibrary的引用改为项目引用(推荐,若允许)

如果CommonLibrary是本地项目,直接替换SourceGenerator.csproj中的NuGet引用为项目引用:

<!-- 替换原有PackageReference -->
<ItemGroup>
    <!-- <PackageReference Include="CommonLibrary" Version="1.0.0" IncludeInPackage="true" /> -->
    <ProjectReference Include="../CommonLibrary/CommonLibrary.csproj" />
</ItemGroup>

这种方式下MSBuild会自动处理依赖传递,测试项目引用生成器时会自动获取CommonLibrary的输出,无需额外配置。

验证步骤

  1. 清理所有项目的bin和obj目录
  2. 重新构建整个解决方案
  3. 运行集成测试项目,确认生成器能正常加载并工作

内容的提问来源于stack exchange,提问作者Paul Dubsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:53:13