Home > Back-end >  Source generator with physical files on disk causing ambiguity
Source generator with physical files on disk causing ambiguity

Time:03-17

I'm working on a project where I want to generate cs classes based on JSON file that defines a set of exceptions. I looked into different options and trying source generator now. In my project, I want to generate the files and have them under my JSON file in the hierarchy not under analyzers (default behavior). For that I used :

<PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild>
    <CompilerGeneratedFilesOutputPath>GeneratedFiles</CompilerGeneratedFilesOutputPath>
  </PropertyGroup>

I'm facing two issues now with my project, first is whenever I try to deserialize the json file (additional file) to my own model using Newtonsoft, I get this error.

CSC : warning CS8785: Generator 'BaseExceptionGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'FileNotFoundException' with message 'Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.'

The second issue, when I build and generate the files under generated folder, I'll have the same files (one under analyzers and one under this folder) which cause ambiguity whenever I try to call a method of the generated code.

Severity    Code    Description Project File    Line    Suppression State
Error   CS0111  Type 'Hello' already defines a member called 'Display' with the same parameter types    SourceGeneratorTest ..\SourceGeneratorTest\SourceGeneratorTest\Generators\SoruceGenerator.BaseExceptionGenerator\BaseException.cs   9   Active

Code repo: https://github.com/KhaledSamir/SourceGeneratorTest

Am I doing something wrong here?

CodePudding user response:

For anyone who came accross same issues, I found out that the solutions for the issues are:

1- CSC : warning CS8785: Generator 'BaseExceptionGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'FileNotFoundException' with message 'Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.'

Followed the cookbook and got it fixed.

2- Error CS0111 Type 'Hello' already defines a member called 'Display' with the same parameter types SourceGeneratorTest ..\SourceGeneratorTest\SourceGeneratorTest\Generators\SoruceGenerator.BaseExceptionGenerator\BaseException.cs 9 Active

Had to remove it from the compile, check this link out. Basically did something like :

<ItemGroup>
    <Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>
  • Related