WhiteleyJ
WhiteleyJ

Reputation: 1691

Roslyn Source Generator not generating any source in a .net framework 4.7.2

Probably a simple learning issue, but I'm attempting to use the new roslyn source generators to automatically generate some source code for .net framework 4.7.2 (mvc is the goal, but I'll be happy if it worked in my test console app).

Here's my code

    [Generator]
    public class GenerateCommand : ISourceGenerator
    {
        public const string TestCode = @"
namespace Test
{
    public static class Hello
    {
        public static string World = ""Hi from generated code."";
    }
}";

        public void Initialize(InitializationContext context) { }

        public void Execute(SourceGeneratorContext context)
        {
            context.AddSource("Hint_Hello_World", SourceText.From(TestCode, Encoding.UTF8));
        }

        public void Test()
        {
            var x = Test.Hello.World;  // <-- Refuses to build.
        }
    }
}

Package versions are Microsoft.CodeAnalysis.CSharp v 3.7.0 (and associated roslyn stuff)

This seems to be about as simple as I can make it and it seems to work if I'm targeting .net core, it's just when I'm trying to add it to a framework project that it does nothing. No errors, no output messages, just not running or generating source.

Any help would be appreciated.

Upvotes: 5

Views: 7650

Answers (2)

Chris Sienkiewicz
Chris Sienkiewicz

Reputation: 745

Update: As of Roslyn 3.8 / Visual Studio 16.8 source generators are no longer behind a preview flag, and should work for any language version or target framework.

Ensure you check out the Breaking changes section of the cookbook to address any API differences between preview and release.


Currently source generators are gated behind <langversion>preview</langversion> as they aren't a released feature, and we don't want customers accidentally using them without realizing it.~~

At release time we'll remove the language version restriction and they'll work on any supported Roslyn compiler, although it will be up to the individual generator authors to ensure that the code they generate is correct for the project options the user has selected.

Upvotes: 7

MindSwipe
MindSwipe

Reputation: 7895

Edit thanks to Chris Sienkiewicz: Currently source code generators are gated behind the preview language version and thus not available for other .NET versions than .NET 5. This will however change once source code generators are released and stable.


Old Answer:

Source code generators are a .NET (Core) 5/ C# 9 feature, there is no way to get it to work with .NET Framework (or .NET Core != 5). If you need to generate code at compile time, you have a few options:

  1. Use a T4 template
  2. Add a pre-build event
  3. Use a NuGet package like Clarius.TransformOnBuild

Upvotes: 0

Related Questions