According to the Incremental Generators documentation, an incremental generator will be called exactly once by the host regardless of how many projects are involved in the compilation:
IIncrementalGenerator has an Initialize method that is called by the host exactly once, regardless of the number of further compilations that may occur. For instance a host with multiple loaded projects may share the same generator instance across multiple projects, and will only call Initialize a single time for the lifetime of the host.
However, in practice, context.CompilationProvider
is an IncrementalValueProvider<Compilation>
providing a single compilation object.
This single compilation object has an Assembly
property which is documented as...
The IAssemblySymbol that represents the assembly being created.
...implying that the compilation object represents the compilation of a single project.
For my use-case, I'm trying to add a new source file to each project that fits a certain criterion (references a particular assembly), so I'm not sure how to proceed when the generator is only provided with a single compilation object, and that compilation object seems to only refer to one assembly.
So my main question is:
What is going on here, given that an incremental generator is run once for multiple projects, but the compilation object seems to refer to a single project?
The Compilation
object indeed represents a single compilation. But if multiple projects reference the generator, the generator is going to run for all those different compilations, even if the host chooses to call Initialize
once.
What is defined in Initialize
is a "pipeline", so the pipeline itself will be executed for all projects/compilations that reference the generator.
Meaning that the host only needs to call Initialize
once to figure out the pipeline, but then the pipeline itself is called as necessary.