C# Source Generators allow you to generate and compile source code dynamically. You can read more about them in this previous article.
In my series on Microsoft Feature Management, part 2 showed how to reduce magic strings by using an enum.
EDIT: my Feature Management Pluralsight training course is now available.
Using this approach still requires that the enum and the configuration file be manually kept in sync.
One use case for C# Source Generators (that are currently in preview) is to generate code from a file in the project, for example generating a class from an XML settings file.
We can process any external file in a source generator, including json files such as appsettings.json.
This means that if the feature flags are defined in the appsettings.json file, we can create a source generator to read this file and output an enum containing all the features that have been defined in the appsettings.json. This means that the feature flags in the app will always be in sync with configuration file. It also means that if you were to remove a flag from the appsettings.json then compilation would break if you were still referencing the feature flag in the app.
Creating a C# Source Generator
To get this all to work in Visual Studio 2019 Preview first create a new .NET Standard 2.0 class library project called FeatureFlagGenerator.
Modify the FeatureFlagGenerator.csproj to the following:
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.6.0-3.20207.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.0.0-beta2.final" PrivateAssets="all" />
Next add a new class called FeatureFlagEnumGenerator with the following code:
public class FeatureFlagEnumGenerator : ISourceGenerator
public void Execute(SourceGeneratorContext context)
IEnumerable<AdditionalText> files = context.AdditionalFiles.Where(at => at.Path.EndsWith("appsettings.json"));
AdditionalText appsettings = files.First();
StringBuilder enumString = new StringBuilder();
enumString.AppendLine(" public enum GeneratedFeatureFlags");
// Doing this manually because referencing JsonDocument etc causes unknown errors
// Not very robust code, POC only
bool isInFeatureManagamentSection = false;
foreach (var line in appsettings.GetText(context.CancellationToken).Lines)
if (isInFeatureManagamentSection && line.ToString().Contains("}"))
isInFeatureManagamentSection = false;
int featureNameStartIndex = line.ToString().IndexOf('"')+1;
int featureNameEndIndex = line.ToString().IndexOf(':')-1;
enumString.AppendLine(line.ToString().Substring(featureNameStartIndex, featureNameEndIndex - featureNameStartIndex) + ",");
isInFeatureManagamentSection = true;
SourceText sourceText = SourceText.From(enumString.ToString(), Encoding.UTF8);
const string desiredFileName = "GeneratedFeaturesEnum.cs";
public void Initialize(InitializationContext context)
// Advanced usage
Essentially the preceding code will search for the appsettings.json file in the project where the source generator is being used and then find all the configured feature flag names - for some reason trying to use System.Text.Json was causing errors so I implemented a very clunky solution using string manipulation.
Using a C# Source Generator
Now the generator is defined, it can be used in another project.
Go and add a new ASP.NET Core MVC project to the solution and modify the .csproj file to the following:
<PackageReference Include="Microsoft.FeatureManagement.AspNetCore" Version="2.0.0" />
<ProjectReference Include="..\FeatureFlagGenerator\FeatureFlagGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
There is a secret ingredient in the preceding project file and that is the AdditionalFiles Include="appsettings.json" part. This makes the file available to C# Source Generators and took me a while to work out.
Now when the web application is built, the source generator will run and create an enum with every configured flag name.
For example given the following appsettings.json:
This will generate and compile the following into the web application dll:
public enum GeneratedFeatureFlags
Notice the Printing and LiveChat enum values come from the appsettings FeatureManagement section.
Now the feature flags can be referenced in code:
if (await _featureManager.IsEnabledAsync(nameof(GeneratedCode.GeneratedFeatureFlags.Printing)))
ViewData["PrintMessage"] = "On";
ViewData["PrintMessage"] = "Off";
Or in the UI:
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Print">Print Preview</a>
It is these kinds of use cases, where there would otherwise be manual boilerplate code work, that C# Source Generators will be really useful.
Be sure to check out my Microsoft Feature Management Pluralsight course get started watching with a free trial.