简体   繁体   中英

Roslyn source generator is "ignored"?

I'm creating a simple Roslyn Source Generator. The generator seems to work well in debug, correctly generating the desired class. However, when referencing it from another project in the solution, a red icon is shown near it with the "Ignored" tooltip and no output is produced:

忽略!

The generator code is very simple:

namespace CompetencesSourceGenerator
{
    using Microsoft.CodeAnalysis;

    [Generator]
    public class CompetenceNamesGenerator: CompetenceGeneratorBase
    {
        public override void Execute(GeneratorExecutionContext context)
        {
            context.AddSource(
                "CompetenceNames.g.cs",
                @"namespace Foo { public class Bar { } }"
            );
        }
    }
}

I checked the following:

  • Generator project targets .NET Standard 2.0
  • Referencing project targets .NET 6
  • Both Microsoft.CodeAnalysis.CSharp and Microsoft.CodeAnalysis.Analyzers in generator project are up to date
  • VS is up to date (17.4.4)
  • .NET Compiler Platform SDK is installed

Why does it not work?

So apparently, the issue was caused by three factors, the combination of which resulted in a very confusing UX:

  • The "Ignored" icon does indeed relate to the files emitted by the generator, not the generator itself. It would have made much more sense to display it next to each file, I have no idea why it works the way it does.
  • The contents of the generated files does not update in the UI. The generator runs, so you will see compilation errors when you emit incorrect code "right away". To view the actual source, you need to close VS altogether, reopen it, rebuild the project and only then view the source.
  • Referencing the generator from a project in the same solution is kinda wonky, because sometimes it does not run on "Rebuild all".

Worth mentioning that in Rider everything works just as expected, so I hope they fix this behavior in VS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM