调试正常但编译时SourceGenerator无法加载Humanizer包的问题
问题根因
调试时正常但编译宿主项目失败,是因为你的SourceGenerator依赖的Humanizer程序集没有被放到NuGet包的编译器可探测路径里。调试环境会自动处理依赖加载,但正式编译时,Roslyn只会从SourceGenerator NuGet包的analyzers/dotnet/cs目录加载关联程序集——哪怕你把Humanizer塞进了NuGet包,位置不对也找不到。
修复步骤
修改TestSourceGenerator.csproj,做以下三处配置:
1. 修正Humanizer.Core的包引用
把原有的Humanizer包引用改成这样:
<PackageReference Include="Humanizer.Core" Version="2.14.1"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference>
PrivateAssets="all":保证这个依赖不会传递给用了你SourceGenerator的项目,符合你的需求。IncludeAssets:确保Humanizer的所有必要文件被纳入当前项目,供SourceGenerator调用。
2. 添加依赖复制与打包目标
在.csproj里加一段目标代码,把Humanizer的dll复制到SourceGenerator输出目录,并且打包时放到analyzers/dotnet/cs目录:
<Target Name="CopyGeneratorDependencies" AfterTargets="Build"> <ItemGroup> <HumanizerAssemblies Include="$(NuGetPackageRoot)humanizer.core\2.14.1\lib\netstandard2.0\*.dll" /> </ItemGroup> <Copy SourceFiles="@(HumanizerAssemblies)" DestinationFolder="$(OutputPath)" /> </Target> <Target Name="IncludeDependenciesInPackage" BeforeTargets="Pack"> <ItemGroup> <AnalyzerFiles Include="$(OutputPath)Humanizer.dll" /> <AnalyzerFiles Include="$(OutputPath)Humanizer.Core.dll" /> </ItemGroup> <ItemGroup> <None Include="@(AnalyzerFiles)" Pack="true" PackagePath="analyzers/dotnet/cs" /> </ItemGroup> </Target>
注意:把代码里的2.14.1换成你实际用的Humanizer版本号。
3. 标记为Roslyn组件
在.csproj的<PropertyGroup>里加一行:
<IsRoslynComponent>true</IsRoslynComponent>
这个属性会让MSBuild自动适配Roslyn组件的打包规则,避免额外的路径问题。
验证方法
- 重新打包SourceGenerator:执行
dotnet pack - 更新ConsoleApp1里的TestSourceGenerator包引用到新打包的版本
- 直接编译ConsoleApp1:
dotnet build,此时应该不会再报找不到Humanizer的错误
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

