When using C# source generators, you will notice that ISourceGenerator is obsolete. It’s time to switch to the new IIncrementalGenerator. Below are the basic usage instructions and the configuration for the .csproj file.
Suppose we have the following project structure:
Example/Example.csproj
Example.sln
To implement code generation for Example.csproj, we need to create a dedicated subproject specifically for generating code, which should be of the type Class Library. In this case, it is named Example.SourceGen.csproj:
Example/Example.csproj
Example.SourceGen/Example.SourceGen.csproj
Example.sln
The minimal configuration for Example.SourceGen.csproj is as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>13</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.0.0-1.25277.114">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
</ItemGroup>
</Project>
Note that this is almost the most minimal configuration, and its functions are as follows:
<TargetFramework>netstandard2.0</TargetFramework> Require this setting. For details, see https://github.com/dotnet/roslyn/blob/main/docs/roslyn-analyzers/rules/RS1041.md<LangVersion>13</LangVersion> Using the default, outdated C# version in the Example.SourceGen.csproj project is clearly insufficient, so we can set the language version separately.<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> Required option.<IsRoslynComponent>true</IsRoslynComponent> Required option.Microsoft.CodeAnalysis.Analyzers 和 Microsoft.CodeAnalysis.CSharp The subproject must include at least these two packages.Then simply reference the subproject in the main project:
<ItemGroup>
<ProjectReference Include="../Example.SourceGen/Example.SourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
Then the task is complete! We can create a Gen.cs file in the subproject and start writing our generator code:
// Gen.cs under Example.SourceGen/Example.SourceGen.csproj
[Generator]
public class ScriptRegisterGen : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// code here
context.RegisterSourceOutput(classNames, (ctx, names) =>
{
// code here
ctx.AddSource("xxx.g.cs", source);
});
}
}