0

我正在尝试设置一个基于附加文件生成代码的源生成器。

源生成器实际运行,但我的问题是只有第一个: context.AddSource实际发出代码。

当我去时,Solution Explorer -> Dependencies -> Analyzers -> <GeneratorName>我只能看到一个正在生成的文件,在使用调试器查看后,它对应于第一个context.AddSource. 调试时,我实际上可以看到生成器遍历我的foreach循环并调用context.AddSource,但该代码并未添加到编译中。

.csproj我添加的引用项目中(我用正确的路径替换了路径):

  <ItemGroup>
    <ProjectReference Include="path-to-generator.csproj"
                      OutputItemType="Analyzer"
                      ReferenceOutputAssembly="false" />
  </ItemGroup>

  <PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
  </PropertyGroup>

并且.csproj生成器是:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
        <LangVersion>8</LangVersion>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
        <PrivateAssets>all</PrivateAssets>
        <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      </PackageReference>
      <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.11.0" PrivateAssets="all" />
    </ItemGroup>
</Project>

这是我的Execute方法:

        public void Execute(GeneratorExecutionContext context)
        {
            var @namespace = GetNamespace(context.Compilation.AssemblyName);
            var resxFiles = context.AdditionalFiles
                .Where(af => af.Path.EndsWith(".resx"))
                .Where(af => Path.GetFileNameWithoutExtension(af.Path) == PathUtils.GetBaseName(af.Path));
            var displayResourcesGenerator = new DisplayResourcesGenerator();
            var displayResourcesWrapperGenerator = new DisplayResourcesWrapperGenerator();

            context.AddSource(
                "DisplayResourcesWrapper.cs",
                displayResourcesWrapperGenerator.Generate(null, null, @namespace)
            );
            

            foreach (var resxFile in resxFiles)
            {
                var resxStream = File.OpenRead(resxFile.Path);
                var resxName = Path.GetFileNameWithoutExtension(resxFile.Path);

                context.AddSource(
                    $"{resxName}.cs",
                    displayResourcesGenerator.Generate(resxStream, resxFile.Path,  @namespace)
                );
            }
        }
4

0 回答 0