Search code examples
c#.netcode-generationclass-librarysourcegenerators

Source Generators for class library project in c#


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.


Solution

  • Assuming that you have followed the docs to a tee, the following should be the issue:

    // Find the main method
    var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);
    

    As comment states this will find the main method which library project obviously does not have, so based on the sources and docs:

    Returns the Main method that will serves as the entry point of the assembly, if it is executable (and not a script).

    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:

    public void Initialize(GeneratorInitializationContext context)
    {
        context.RegisterForSyntaxNotifications(() => new RecordSyntaxReceiver());
    }
    

    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.