50 lines
2.5 KiB
Markdown
50 lines
2.5 KiB
Markdown
# Source Generator Demo
|
|
This is an attempt at a bare-bones minimal source generator in an attemp to evolve to a project template or other boilerplate approach to creating source generators.
|
|
|
|
## GeneratorConsole and HelloWorldGenerator
|
|
The HelloWorldGenerator should produce a static class with a single static method that can easily by called by any project that properly references the analyzer project, GeneratorLib. It should be called like this:
|
|
|
|
```
|
|
HelloWorldNamespace.HelloWorld.SayHello();
|
|
```
|
|
|
|
## How to Greate a Source Generator
|
|
|
|
* Create a new class library for the generators.
|
|
* Change the class library target framework to "netstandard2.0", even if there is a newer version. This is a "plugin" for the analyzer system and must match its version.
|
|
* Manually add appropriate attributes to the .csproj file as listed below.
|
|
* Add appropriate NuGet references listed below.
|
|
|
|
Appropriate attributes for the generator .csproj project file:
|
|
* `<langVersion>12</langVersion>` OR `<langVersion>latest</langVersion>`
|
|
* `<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>`
|
|
* `<IsRoslynComponent>true</IsRoslynComponent>`
|
|
* `<IncludeBuildOutput>false</IncludeBuildOutput>`
|
|
* `<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>`
|
|
|
|
Probably not needed attributes:
|
|
* `<CompilerGeneratedFilesOutputPath>.\GeneratedFiles</CompilerGeneratedFilesOutputPath>`
|
|
|
|
Required NuGet references for generators:
|
|
* `Microsoft.CodeAnalysis.Analyzers`
|
|
* `Microsoft.CodeAnalysis.CSharp`
|
|
|
|
Gen-1 analyzers also needed (Gen-2 probably does not and sometimes gives you a warning to remove it):
|
|
* `Microsoft.CodeAnalysis.CSharp.Workspaces`
|
|
|
|
## How to Consume a Source Generator
|
|
Create a new application of any kind or a new shared class library. Add a reference to the source generator library. This can be a NuGet reference. While under development, it will probably be a project reference. If it is a project reference, you will need to manually modify the reference in the consumer project's .csproj file manually to tell it that the assembly is an analyzer. It will need the `OutputItemType` attribute at least. Example:
|
|
|
|
```
|
|
<ItemGroup>
|
|
<ProjectReference Include="..\GeneratorLib\GeneratorLib.csproj"
|
|
OutputItemType="Analyzer"
|
|
ReferenceOutputAssembly="false"/>
|
|
</ItemGroup>
|
|
```
|
|
|
|
## Issues
|
|
Generated types do not get generated. Generated code does not appear in generator output, even though the specified generated code folder is created. Types are not available in the consuming project and do not show up in the Object Inspector.
|
|
|
|
## Notes
|
|
Notes go here. |