alebo611
alebo611

Reputation: 1280

C# Source code generator dependent on existing class

I need to generate source code that will inherit from an abstract class that I already have present in my project, and the source generator project itself compiles. But when the compiler complains that the generated sources does not recognize the abstract class, even though its in the same project. Do I need to tell the generator project to have runtime dependencies to itself in some way?

EDIT: Im using Microsoft.CodeAnalysis.CSharp. Here is the code describing the sitation: https://github.com/alebo611/csharpsourcegenproblem/tree/main/MyGeneratorProject

That is, I just want to generate a subclass of the already defined "Vehicle". If you run it in Visual Studio, you will get following error:

Error CS0246 The type or namespace name 'Vehicle' could not be found (are you missing a using directive or an assembly reference?) Consumer generated.cs

And adding "Using ApplicationContext" does not help, it will complain it does not find the context.

Upvotes: 2

Views: 1669

Answers (1)

pschill
pschill

Reputation: 5569

Source generators are used to generate new source code that will then be compiled and added to your assembly. This means that usually, the source generator assembly is only required at build time. Therefore, when consuming a source generator via ProjectReference, you usually use OutputItemType="Analyzer" and ReferenceOutputAssembly="false":

<ProjectReference Include="SourceGenerator.csproj"
                  OutputItemType="Analyzer"
                  ReferenceOutputAssembly="false" />

In your example however, the source generator assembly contains a type Vehicle that is required by the consuming assembly. This means that the source generator assembly must be referenced by the consumer, so you must omit the ReferenceOutputAssembly parameter:

<ProjectReference Include="SourceGenerator.csproj"
                  OutputItemType="Analyzer" />

It is unfortunate that the consumer must take care of such details of the generator. Fortunately, things are different when consuming the source generator via package. In that case, the package author takes care that assemblies required at build time are stored in analyzers/dotnet/cs within the package and assemblies that are required at runtime are stored in lib/[targetframework].

Upvotes: 5

Related Questions