Source generator is ignored by Visual Studio

270 Views Asked by At

I spent all day trying to run a Source Generator in Visual Studio 2022. I downloaded a few source code and none of them is working. Neither the Microsoft examples. I was trying to use a code to create DTOs from domain classes.

So, I created a simple project ClassLibrary1 based on NETStandard 2.1 and added this CustomGenerator class (code from the Microsoft documentation)

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Text;

namespace ClassLibrary1
{
    [Generator]
    public class CustomGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context) { }

        public void Execute(GeneratorExecutionContext context)
        {
            context.AddSource("myGeneratedFile.cs", SourceText.From(@"
namespace GeneratedNamespace
{
    public class GeneratedClass
    {
        public static void GeneratedMethod()
        {
            // generated code
        }
    }
}", Encoding.UTF8));
        }
    }
}

Then, in another NET7 project, I added the ClassLibrary1 as a reference. I manually changed the project and the result is

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

    <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    </PropertyGroup>

    <ItemGroup>
        <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" 
                          OutputItemType="Analyzer" 
                          ReferenceOutputAssembly="false" />
        <ProjectReference Include="..\DtoGenerator\DtoGenerator.csproj" 
                          OutputItemType="Analyzer" 
                          ReferenceOutputAssembly="false" />
    </ItemGroup>
</Project>

I built and rebuilt the solution and restart Visual Studio. The result is the source generator is ignored.

enter image description here

The project ClassLibrary1 is this

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

    <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.CodeAnalysis" Version="4.7.0" />
        <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" 
            Version="3.3.4">
            <PrivateAssets>all</PrivateAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.CodeAnalysis.CSharp" 
            Version="4.7.0" PrivateAssets="All" />
    </ItemGroup>

    <PropertyGroup>
        <EmitCompilerGeneratedFiles>
            true
        </EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>
            Generated
        </CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>
0

There are 0 best solutions below