Is this possible to generate code with Source Generator in c# into class library project? I would like this auto-generated code to be packed into Nuget package then.
When I try to build a project made according to the Microsoft(https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview) tutorial I encounter the following error:
CSC : warning CS8785: Generator 'HelloSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'NullReferenceException' with message 'Object reference not set to an instance of an object.
The only difference is that I am trying to generate code for a class library project, not a console application.
I tried to do it according to the guide posted on Microsoft's website(https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview), but it assumes generating code for an application that has a console interface.
Assuming that you have followed the docs to a tee, the following should be the issue:
As comment states this will find the main method which library project obviously does not have, so based on the sources and docs:
mainMethod
will be null, hence the exception you see. Usually you want to analyze assembly for some syntax, for example as I do in my currently unfinished generator:Code for receiver can be found here.
Also I highly recommend to go through the linked in the docs Source Generator Samples @github and Source Generators Cookbook.