How to read build variables in Source Generators
I used GitHub copilot to help me create a source generator that reads the schema of a database and generates C# ADO.net code that can call SQL Stored Procedures, Views and Functions in that database (https://github.com/TheJuanitoLearnsShow/Puppy.Ado.SourceGenerator). The connection string to the database is set on a build variable in the consuming csproj file. The problem is that copilot missed the step described in Microsoft’s Source Generator Cookbook . The missing step is to add a CompilerVisibleProperty element to an ItemGroup for each of the build variables you want the source generator to use.
For example, my source generator uses two build variables: DbGen_EnableLiveSchema and DbGen_ConnectionString, so they are defined in the PropertyGroup element in the consuming csproj file:
<DbGen_EnableLiveSchema>true</DbGen_EnableLiveSchema>
<DbGen_ConnectionString>Data Source=.\sqlExpress;Database=AutomatedTESTS_AdoGenerator_SampleDb;Integrated Security=True;TrustServerCertificate=True;</DbGen_ConnectionString>
In addition to the above, I have to add the corresponding CompilerVisibleProperty elements in that same csproj file to allow the source generator to read those variables via the AnalyzerConfigOptionsProvider’s GlobalOptions dictionary:
<ItemGroup>
<CompilerVisibleProperty Include="DbGen_EnableLiveSchema" />
<CompilerVisibleProperty Include="DbGen_ConnectionString" />
</ItemGroup>
C# code reading the variables:
var options = context.AnalyzerConfigOptionsProvider.Select(
(p, _) => new GeneratorOptions(p)); … public GeneratorOptions(AnalyzerConfigOptionsProvider provider)
{
var global = provider.GlobalOptions;
global.TryGetValue("build_property.DbGen_EnableLiveSchema", out var enable);
global.TryGetValue("build_property.DbGen_ConnectionString", out var conn);
EnableLiveSchema = bool.TryParse(enable, out var b) && b;
ConnectionString = conn;
}
Comments