Gating features at compile time with a Roslyn generator
Stop scattering hand-written entitlement checks. A Roslyn source generator emits the guards for you, validates entitlement names against a manifest, and fails the build on a typo.
Entitlement checks have a way of multiplying. One feature needs export.pdf, another needs reports.scheduled, a third needs a seats limit — and each one grows its own little block of “resolve the license, read the entitlement, decide what to do on failure.” Copy that block around a codebase and it drifts: one call site throws, another returns false, a third forgets to check at all, and somewhere a string literal says exprot.pdf and silently denies a feature to every paying customer. The checks are individually trivial and collectively a liability.
This is exactly the kind of repetitive, error-prone, mechanical code a Roslyn source generator exists to remove. Instead of writing the guard, you declare the gate with an attribute and let the generator emit a correct, uniform guard at compile time — and, because the generator sees your whole compilation, it can validate every entitlement name against your declared catalog and fail the build on a typo. This post builds that generator against the Keyright SDK.
What we are building
You decorate a partial method with the entitlement it requires:
public static partial class Features
{
[Gate("export.pdf")]
public static partial void RequirePdfExport();
[Gate("export.pdf", Kind = GateKind.Limit, Limit = "pages-per-day")]
public static partial int PdfPageBudget();
}
The generator fills in the bodies. At a call site you write one line and the branching is gone:
public byte[] Export(Document doc)
{
Features.RequirePdfExport(); // throws LicenseException if not entitled
int budget = Features.PdfPageBudget(); // the numeric limit from the signed license
...
}
Every gate now reads the same way, fails closed the same way, and names an entitlement the compiler has already confirmed exists. The diagram below shows the two halves — what happens at build time, and what the emitted code does at runtime.
The marker attribute
Source generators ship their own attributes so consumers do not reference a separate assembly. Emit it during post-initialization, before any user code is analyzed:
private const string AttributeSource = """
namespace Acme.Licensing;
[System.AttributeUsage(System.AttributeTargets.Method)]
internal sealed class GateAttribute : System.Attribute
{
public GateAttribute(string entitlement) => Entitlement = entitlement;
public string Entitlement { get; }
public GateKind Kind { get; set; } = GateKind.Require;
public string? Limit { get; set; }
}
internal enum GateKind { Require, Limit }
""";
Require emits a void guard that throws when the entitlement is absent; Limit emits a method returning the numeric limit the signed license carries for a named key.
The incremental generator
Use IIncrementalGenerator — the cached, pull-based model that only re-runs when relevant inputs change. Three inputs feed it: the attribute (registered up front), the annotated methods, and the entitlement manifest supplied as an AdditionalFile.
[Generator]
public sealed class EntitlementGateGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(ctx =>
ctx.AddSource("GateAttribute.g.cs", AttributeSource));
IncrementalValuesProvider<GateModel> gates = context.SyntaxProvider
.ForAttributeWithMetadataName(
"Acme.Licensing.GateAttribute",
predicate: static (node, _) => node is MethodDeclarationSyntax m
&& m.Modifiers.Any(SyntaxKind.PartialKeyword),
transform: static (ctx, _) => GateModel.From(ctx))
.Where(static m => m is not null)!;
IncrementalValueProvider<ImmutableHashSet<string>> manifest = context
.AdditionalTextsProvider
.Where(static f => Path.GetFileName(f.Path) == "entitlements.json")
.Select(static (f, ct) => f.GetText(ct)?.ToString())
.Collect()
.Select(static (texts, _) => ManifestParser.Names(texts));
context.RegisterSourceOutput(gates.Combine(manifest),
static (spc, pair) => Emit(spc, pair.Left, pair.Right));
}
}
ForAttributeWithMetadataName is the fast path added in .NET 7’s Roslyn: it is driven by the attribute index rather than by walking every syntax node, so a large solution does not pay for the generator on every keystroke. The predicate narrows to partial methods; the transform lifts each match into a small, equatable GateModel record — namespace, containing type, method name, entitlement, kind, limit key, and the attribute’s Location for diagnostics. Keeping that model a value type with structural equality is what lets the incremental pipeline cache correctly.
Validating names against the manifest
This is where the generator earns its place over a snippet. A single declared catalog — the same entitlements.json your issuing configuration already owns — lists every entitlement the product knows about. Reference it from the consuming project so the generator can read it:
<ItemGroup>
<AdditionalFiles Include="entitlements.json" />
</ItemGroup>
In Emit, compare each gate’s entitlement against the manifest and report a build error when it is unknown — but only when a manifest was actually supplied, so projects that opt out are not forced into it:
private static readonly DiagnosticDescriptor UnknownEntitlement = new(
id: "KR0001",
title: "Unknown entitlement",
messageFormat: "Entitlement '{0}' is not declared in entitlements.json",
category: "Keyright",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static void Emit(SourceProductionContext spc, GateModel g,
ImmutableHashSet<string> manifest)
{
if (!manifest.IsEmpty && !manifest.Contains(g.Entitlement))
{
spc.ReportDiagnostic(Diagnostic.Create(
UnknownEntitlement, g.Location, g.Entitlement));
return;
}
spc.AddSource($"{g.TypeName}_{g.MethodName}.g.cs", Render(g));
}
Now [Gate("exprot.pdf")] is a red squiggle and a failed build with message KR0001: Entitlement 'exprot.pdf' is not declared in entitlements.json, caught at the moment of the typo rather than six weeks later when a customer cannot export. That is the whole argument for doing this in a generator: the compiler becomes the thing that keeps your gates honest.
Rendering the guard
The emitted body is deliberately boring. It resolves a cached LicenseInfo and asks the entitlement set — the same two calls you would write by hand, now written identically every time:
private static string Render(GateModel g) => g.Kind switch
{
GateKind.Require => $$"""
// <auto-generated/>
namespace {{g.Namespace}};
partial class {{g.TypeName}}
{
static partial void {{g.MethodName}}()
{
var info = LicenseGate.Current;
if (!info.Entitlements.IsEnabled("{{g.Entitlement}}"))
throw new LicenseException("{{g.Entitlement}}", info.Status);
}
}
""",
GateKind.Limit => $$"""
// <auto-generated/>
namespace {{g.Namespace}};
partial class {{g.TypeName}}
{
static partial int {{g.MethodName}}()
=> (int)LicenseGate.Current.Entitlements.GetLimit("{{g.Limit}}");
}
""",
_ => ""
};
LicenseGate is the one piece of ordinary runtime code, holding a cached LicenseInfo so each guard is a field read, not a re-verification:
public static class LicenseGate
{
private static readonly Lazy<KeyrightClient> Client = new(() =>
KeyrightClient.Initialize(new KeyrightOptions
{
Product = "Acme.Pdf",
PublicKeyBase64 = AcmePublicKey.Base64, // verify-only; safe to ship
ServiceUrl = "https://license.acme.example" // your self-hosted service
}));
private static volatile LicenseInfo? _cached;
public static LicenseInfo Current => _cached ??= Client.Value.Validate();
public static void Refresh() => _cached = Client.Value.Validate();
}
Validate() is pure local computation against the embedded public key — it never throws and fails closed, returning a Free edition LicenseInfo on any problem — so an absent or unknown entitlement reads as disabled and the guard throws. Online activation runs once to cache the lease; everything the generated gates do after that is offline.
What the generator is not
The honest caveat matters. A source generator emits C#; the compiled guard is as visible to a decompiler as anything you would write yourself, and nothing about generating it makes the IsEnabled branch harder to patch out. The security does not live in the gate — it lives in the signature. Validate() verifies the signed license against a public key an attacker cannot forge against, and that check is the boundary. The generator’s job is narrower and still worth doing: it makes every gate consistent, impossible to forget at a decorated call site, and impossible to misname past a build. If you also want the runtime check itself resistant to tampering, that is a job for obfuscation and anti-tamper layered on top — a different tool for a different threat. Used for what it is, the generator turns a scattered, drift-prone pattern into one declaration the compiler verifies for you.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.