Native AOT
RoslynRules compiles rule expressions at runtime with Roslyn. That is powerful, but Roslyn compilation and the reflection it depends on are not available under Native AOT (and are trimmed away by aggressive trimming). For those deployments RoslynRules offers a second path: compile the rules at build time with a source generator, then bind the generated delegates at runtime instead of calling Compile(...).
- JIT / normal apps — keep using
Compile(...). Nothing changes. - Native AOT apps — add the
RoslynRules.SourceGeneratorpackage, declare your rules so the generator can see them at build time, and callBindCompiled(...)instead ofCompile(...).
No runtime Roslyn, no reflection, no runtime assembly loading.
A rule takes exactly one parameter. To pass several values, wrap them in a struct/class and reference its members in the expression (
p.X,p.Y). See migration.
How it works
- At build time the
RoslynRules.SourceGeneratorreads your rule definitions (from any of the three front-ends below) and emits:- typed, cast-based invoker methods compiled as ordinary C# by the AOT toolchain, and
- one
RoslynRules.Generated.CompiledRuleProviderthat implementsRoslynRules.Aot.ICompiledRuleProvider, mapping each rule’sIdto aCompiledRuleBinding.
- At runtime you build your
Workflow/Ruleas usual (the ruleIdvalues must match the definitions), then callBindCompiledinstead ofCompile:
var workflow = new Workflow { Rules = { new Rule(ruleId) { Expression = "c.Age >= 18" } } };
workflow.BindCompiled(new RoslynRules.Generated.CompiledRuleProvider()); // no Roslyn
var result = workflow.Execute(new RuleParameter("c", typeof(Customer), customer)).First();
BindCompiled sets the same compiled delegates Compile would, then locks the rule. It is not gated by AOT detection, so the same code runs identically on JIT and AOT.
Why Id matters
The generated provider is keyed by rule Id (a GUID). The Id on your runtime Rule must equal the Id in the build-time definition so BindCompiled can find the generated delegate. The JSON front-end avoids any duplication because the generator and your runtime loader read the same file.
Setup
Add the generator as an analyzer-only (opt-in) reference:
<PackageReference Include="RoslynRules.SourceGenerator" Version="x.y.z" PrivateAssets="all" />
(Within this repo, reference the project with OutputItemType="Analyzer" ReferenceOutputAssembly="false".)
Front-ends
You can declare rules for the generator in three ways; mix and match freely — they all feed the one generated CompiledRuleProvider.
1. Assembly attributes
[assembly: RoslynRules.Generated.CompiledRule(
"7b2e4c10-0000-0000-0000-000000000001", // Id — must match the runtime Rule.Id
"c", // parameter name used in the expression
typeof(Customer), // parameter type
"c.Age >= 18 && c.Country == \"US\"")] // expression
// Optional named argument: Action = "..."
Repeat the attribute per rule. typeof(Customer) gives the generator the exact type, so the emitted invoker casts without reflection.
2. Partial rules class
[RoslynRules.Generated.RoslynRulesClass]
public static partial class EligibilityRules
{
[RoslynRules.Generated.Rule("7b2e4c10-0000-0000-0000-000000000002", "o.Total >= 100m")]
public static partial bool IsLargeOrder(Order o);
}
The generator implements the partial method body and registers the rule in the provider. The method signature supplies the parameter name/type and return type (bool, or Task<bool> for an async rule). The generated method is also directly callable.
3. JSON definition files
Author a JSON file and list it as an AdditionalFiles entry flagged for the generator:
<ItemGroup>
<AdditionalFiles Include="Rules\eligibility.json" IsRoslynRulesDefinition="true" />
<CompilerVisibleItemMetadata Include="AdditionalFiles" MetadataName="IsRoslynRulesDefinition" />
</ItemGroup>
{
"parameter": { "name": "c", "type": "MyApp.Models.Customer" },
"rules": [
{ "id": "7b2e4c10-0000-0000-0000-000000000003", "expression": "c.Age >= 18", "action": null }
]
}
parameter is workflow-level (one parameter type for the file’s rules), matching Workflow.Compile(oneParameter). type is a fully-qualified type name resolved in your project. The same file can be loaded at runtime to build the Workflow (the extra parameter field is ignored by the runtime loader), so the rule Id values line up automatically.
Async rules
Expressions/actions that await are detected automatically. The generated binding uses an async invoker, and ExecuteAsync awaits it genuinely (no blocking).
Diagnostics
| Id | Meaning |
|---|---|
RR0001 | Duplicate compiled rule Id — only the first is emitted. |
RR0002 | A rule Id is not a valid GUID and was skipped. |
Publishing with Native AOT
The rule path adds no reflection or dynamic code, so a BindCompiled-only app publishes cleanly:
dotnet publish -c Release -r linux-x64 -p:PublishAot=true
Setting <PublishAot>true</PublishAot> also turns on the trim/AOT analyzers for ordinary builds, so dotnet build flags any unsafe path early. See RoslynRules.Aot.Sample in the repository for a complete, publishable example; the AOT Compatibility CI workflow publishes and runs it natively as a gate.
Caveat
Do not call Compile(...), CompiledWorkflow.Compile(...), SnapshotManager.CompileAndSnapshot/ RestoreAndCompile(...), or the instance Rule.ValidateSemantics(...) on the AOT path — those require Roslyn and throw AotCompatibilityException when dynamic code is unavailable. Use BindCompiled and the generator instead. Structural APIs (building rules, Validate(), execution) are AOT-safe.