1

I referred to this official tutorial: https://learn.microsoft.com/zh-cn/dotnet/csharp/roslyn-sdk/source-generators-overview , but it didn't work as expected.

The Source Generator project I created contains the following two files:

TestSourceGenerator.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>latest</LangVersion>
    <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
  </ItemGroup>
</Project>

TestGenerator.cs

using Microsoft.CodeAnalysis;

namespace TestSourceGenerator
{
    [Generator]
    public class TestGenerator : ISourceGenerator
    {
        public void Execute(GeneratorExecutionContext context)
        {
            var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);

            string source = $@"// <auto-generated/>
using System;

namespace {mainMethod.ContainingNamespace.ToDisplayString()}
{{
    public static partial class {mainMethod.ContainingType.Name}
    {{
        static partial void HelloFrom(string name) =>
            Console.WriteLine($""Generator says: Hi from '{{name}}'"");
    }}
}}
";
            var typeName = mainMethod.ContainingType.Name;

            context.AddSource($"{typeName}.g.cs", source);
        }

        public void Initialize(GeneratorInitializationContext context)
        {
            
        }
    }
}

And then i create a console project to reference it like tutorial: Test.csproj

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

  <ItemGroup>
    <ProjectReference 
      Include="..\TestSourceGenerator\TestSourceGenerator.csproj" 
      OutputType="Analyzer"
      ReferenceOutputAssembly="false"
    />
  </ItemGroup>

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Program.cs

namespace Test;

partial class Program
{
    static void Main(string[] args)
    {
        HelloFrom("Generated Code");
    }

    static partial void HelloFrom(string name);
}

I use dotnet run in terminel to run this Test project, but there is no output.

At which step did i go wrong?

dotnet --info

.NET SDK:
 Version:   7.0.120
 Commit:    25b977658c

运行时环境:
 OS Name:     Windows
 OS Version:  10.0.22631
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\7.0.120\

Host:
  Version:      8.0.8
  Architecture: x64
  Commit:       08338fcaa5

.NET SDKs installed:
  6.0.425 [C:\Program Files\dotnet\sdk]
  7.0.120 [C:\Program Files\dotnet\sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 6.0.33 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 7.0.20 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 6.0.33 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 7.0.20 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 8.0.8 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 6.0.33 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
  Microsoft.WindowsDesktop.App 7.0.20 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
  Microsoft.WindowsDesktop.App 8.0.8 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

Other architectures found:
  None

Environment variables:
  Not set

global.json file:
  Not found

Learn more:
  https://aka.ms/dotnet/info

Download .NET:
  https://aka.ms/dotnet/download
5
  • 1
    Do you have any compiler errors? See this post for how to build your solution and how to run your Console App. Commented Aug 19, 2024 at 4:49
  • 1
    Before going too far, can I point you at the github source generators cookbook. Not so much for most of the content but for the notice at the top, that unfortunately hasn't been copied to the article you reference - "Warning: Source generators implementing ISourceGenerator have been deprecated in favor of incremental generators. ... You should implement IIncrementalGenerator instead of ISourceGenerator." Commented Aug 19, 2024 at 5:04
  • 2
    OutputType --> OutputItemType. Is this considered a typo? Commented Aug 19, 2024 at 5:42
  • @shingo thanks for your correction. However, after the modification, there is still no output when running. The strange thing is that when I lower the version of Microsoft.CodeAnalysis.CSharp to 4.2.0, the implementation of the HelloFrom function can be generated normally. Btw, this only works when I run dotnet run -c release for release build. The generator still doesn't seem to work when I run debug build Commented Aug 20, 2024 at 5:01
  • @Damien_The_Unbeliever thanks for pointing the way. I tried using IIncrementalGenerator instead of ISourceGenerator and after making the changes as I replied to shingo, the generator worked fine. But as described in that reply, I am confused why the generator of higher version Microsoft.CodeAnalysis.CSharp does not work properly ? Commented Aug 20, 2024 at 5:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.