Publishing AOT with JasperFx
This guide walks through publishing a .NET application that uses JasperFx (and the rest of the Critter Stack) with Native AOT (dotnet publish /p:PublishAot=true). Native AOT ahead-of-time-compiles the app to a self-contained native binary with no JIT and aggressive trimming, which means:
- Startup is near-instant — no JIT warmup, no Roslyn loading.
- Publish size is small — typically 15-40 MB self-contained, comparable to a Go binary.
- No runtime code generation — anything that needs
Reflection.Emit,Type.MakeGenericType, orActivator.CreateInstance(Type)on a type the trimmer didn't statically see will warn at publish time and may fail at runtime.
AOT publishing has been a supported posture since JasperFx 2.0 for apps that don't need runtime code generation. JasperFx and JasperFx.Events build with IsAotCompatible=true, and JasperFx's CI publishes Native AOT smoke apps on every pull request to keep it that way.
Prerequisites
- .NET 10 SDK
- An application using
TypeLoadMode.Static(see CLI: codegen Command) - Critter Stack packages on the current line: JasperFx 3.x with Weasel 10, Marten 10, Wolverine 7, Polecat 6 or Fisher 2. The 2.x line (Marten 9, Wolverine 6, Polecat 4) supports the same two-phase model
The two-phase model
AOT publishing splits the codegen pipeline across two clearly-distinct phases:
Dev-time is the Roslyn path: you write configuration code, run codegen write (which loads Roslyn + JasperFx.RuntimeCompiler), and the generated *.cs files land in Internal/Generated/ next to your source. You commit those files.
Publish-time is the Roslyn-free path: the published binary contains only the pre-generated code. No Microsoft.CodeAnalysis.*, no JasperFx.RuntimeCompiler, no MakeGenericType on unknown types.
Setup
1. Reference the right packages
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsAotCompatible>true</IsAotCompatible>
<!-- One version for every JasperFx package, including the source generator -->
<JasperFxVersion>2.100.1</JasperFxVersion>
</PropertyGroup>
<!--
PublishAot only for the configuration you publish. Set unconditionally, the SDK also writes
IsDynamicCodeSupported=false into the runtimeconfig that `dotnet run` uses, and
TypeLoadMode.Dynamic then refuses to run in development.
-->
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<PublishAot>true</PublishAot>
</PropertyGroup>
<ItemGroup>
<!-- Critter Stack foundation -->
<PackageReference Include="JasperFx" Version="$(JasperFxVersion)" />
<PackageReference Include="JasperFx.Events" Version="$(JasperFxVersion)" />
<!-- Compile-time only: command, parser and extension manifests for this app -->
<PackageReference Include="JasperFx.SourceGenerator" Version="$(JasperFxVersion)"
PrivateAssets="all" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<!-- Marten / Wolverine / Polecat as needed -->
<!-- <PackageReference Include="Marten" Version="..." /> -->
<!-- <PackageReference Include="WolverineFx" Version="..." /> -->
<!-- <PackageReference Include="Polecat" Version="..." /> -->
</ItemGroup>
<!--
JasperFx.RuntimeCompiler is referenced ONLY at dev-time so `codegen write`
has access to Roslyn. It is intentionally absent from the production publish
so the trimmer drops the entire Microsoft.CodeAnalysis.* graph.
-->
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<PackageReference Include="JasperFx.RuntimeCompiler" Version="..." />
</ItemGroup>
</Project>Key points:
IsAotCompatible=trueturns on the IL2026 / IL2070 / IL2075 / IL3050 analyzers so any new reflective surface in your code surfaces at compile time.PublishAot=truetriggers Native AOT at publish. Keep it out of the configuration you develop in, as the comment above says, or pass-p:PublishAot=truetodotnet publishinstead.JasperFx.SourceGeneratoris what lets the JasperFx command line run inside the native binary (see Running the command line in an AOT binary). The package is namedJasperFx.SourceGenerator; it is an analyzer, so it adds nothing to the published binary.JasperFx.RuntimeCompileris conditional onDebugso the production publish (Configuration=Release) never sees Roslyn. Adjust the condition to whatever fits your build pipeline; the rule is just "not referenced in the AOT publish."
To fail the build on new IL warnings in your own code, promote them with <WarningsAsErrors>IL2026;IL2046;IL2055;IL2065;IL2067;IL2070;IL2072;IL2075;IL2090;IL2091;IL2111;IL3050;IL3051</WarningsAsErrors>, the list the JasperFx AOT smoke-test consumer in CI uses. An app that calls RunJasperFxCommands then has to suppress that call site, as shown below.
2. Configure JasperFx for Static mode
var builder = WebApplication.CreateBuilder(args);
builder.Services.CritterStackDefaults(opts =>
{
opts.Production.GeneratedCodeMode = TypeLoadMode.Static;
// Development can still use Dynamic so iteration is fast
opts.Development.GeneratedCodeMode = TypeLoadMode.Dynamic;
});In Production profile the host loads pre-generated types directly from the compiled assembly. No Roslyn invocation. If a generated type is missing, the app throws at startup rather than silently regenerating — which is the right failure mode for AOT publishing.
Inside a Native AOT image the two dynamic modes are treated differently on purpose: TypeLoadMode.Auto quietly falls back to the static loader, because adapting to the platform is what Auto is for, while an explicit TypeLoadMode.Dynamic throws PlatformNotSupportedException naming codegen write — you asked for something the platform cannot do, and saying so at startup beats the obscure failure it would otherwise reach later.
3. Don't call AddRuntimeCompilation()
JasperFx 2.0 split the runtime compiler into an opt-in seam:
// Calling this in your composition root pulls JasperFx.RuntimeCompiler +
// Microsoft.CodeAnalysis.* into the production graph. Omit it for AOT.
//
// services.AddRuntimeCompilation(); // ← intentionally NOT calledOmitting the call lets the trimmer drop the entire Roslyn graph from the published binary.
Workflow
Dev-time: write the generated code
After every meaningful change to your composition (handlers, projections, document mappings, etc.) regenerate the cached code:
dotnet run -- codegen writeThis produces files under Internal/Generated/ — these go into source control. The codegen output is deterministic across runs (PR #196), so you'll see byte-identical diffs when nothing has changed.
CI integration
A common pattern is to run dotnet run -- codegen write in CI and fail the build if it produces a diff. That catches "someone changed configuration but forgot to regenerate" before it bites the AOT publish.
Publish-time: produce the native binary
dotnet publish -c Release /p:PublishAot=true -r linux-x64 -o ./publishA successful publish produces a single self-contained binary (plus a few native dependency .so / .dll files) under ./publish. The Roslyn graph is gone; the binary loads the pre-generated types out of itself with no compilation.
If publish fails with IL warnings-as-errors, the build output tells you exactly which line in your code (or in a downstream package) reaches a reflective surface that isn't annotated. Common cases:
| Error | Likely cause | Fix |
|---|---|---|
IL2026: …RequiresUnreferencedCodeAttribute on a Critter Stack API | You're calling an API that JasperFx / Marten / Wolverine has annotated [RequiresUnreferencedCode]. | Either avoid the API in the AOT publish path, or wrap the call site with [UnconditionalSuppressMessage] + a justification (and accept that the trim risk is on you). |
IL3050: …RequiresDynamicCodeAttribute on MakeGenericType / Activator.CreateInstance in your own code | You're doing reflection. | Refactor to source-generated code, or to JasperFx.Core.Reflection.GenericFactoryCache.BuildAs<T>(...) with a delegate factory. |
Unable to load type 'X' from assembly 'Y' at runtime | The trimmer dropped a type that was reachable only by reflection. | Annotate the reflective call site with [DynamicallyAccessedMembers] on the relevant Type parameter, or add a [DynamicDependency] to keep the type alive. |
Rooting pre-generated types
There is a trap in the two-phase model above. Pre-generated types are only ever reached reflectively — the host scans the application assembly's exported types and calls Activator.CreateInstance. ILC sees no static reference to any of them, so it trims them, and TypeLoadMode.Static then degrades into a scan that finds nothing. When a code file expected a type, that is an ExpectedTypeMissingException whose message says whether nothing generated reached the binary at all or only that one type is missing, and what to do about each. An application with no generated code expects no types, so it never sees this. A framework that does its own scan and carries on without the result is still quiet, which is why rooting is worth getting right up front.
The fix is to root the generated types from the generated code itself, which is the one place that knows every type involved. JasperFx emits that as an AOT roots companion — a generated class whose single static void method carries a [ModuleInitializer] plus one [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(...))] per rooted type. A module initializer is an unconditional ILC root, so the whole graph is anchored with no application-side code:
// inside an ICodeFile.AssembleTypes(GeneratedAssembly assembly)
assembly.AddAotRoots("AotRoots", new[]
{
"MyApp.Generated.GeneratedHandlerRegistry",
"MyApp.Generated.SomeGeneratedHandler",
"MyApp.Messages.CreateOrder"
});which emits:
// Native AOT rooting companion
[global::System.CodeDom.Compiler.GeneratedCode("JasperFx", "1.0.0")]
public sealed class AotRoots
{
[global::System.Runtime.CompilerServices.ModuleInitializer]
[global::System.Diagnostics.CodeAnalysis.DynamicDependency(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All, typeof(global::MyApp.Generated.GeneratedHandlerRegistry))]
[global::System.Diagnostics.CodeAnalysis.DynamicDependency(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All, typeof(global::MyApp.Generated.SomeGeneratedHandler))]
[global::System.Diagnostics.CodeAnalysis.DynamicDependency(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All, typeof(global::MyApp.Messages.CreateOrder))]
public static void Pin()
{
// Intentionally empty. The [DynamicDependency] attributes above are the payload...
}
}Notes:
- Pass sibling generated types by name (the
IEnumerable<string>overload). They do not exist as runtimeTypes whilecodegen writeis running. There are also overloads takingIEnumerable<Type>for types that do already exist, andIEnumerable<AttributeArg>when you need to mix the two. [DynamicDependency]hasAttributeUsage(Constructor | Field | Method), so it cannot sit on the class — the method is the only legal home for the block.- The companion is C# only. The F# compiler does not honor
ModuleInitializerAttribute(an F# module'sdobindings initialize lazily and are not an ILC root), soAddAotRootsreturnsnulland emits nothing whenassembly.TargetLanguageisfsharprather than emitting rooting that silently does nothing. An assembly assembled on the C# default and then rendered withGenerateFSharpCode()leaves the companion out as well (since 3.7.0), because its by-name roots don't compile as F#. codegen testcompiles eachICodeFileinto its own in-memory assembly, so a sibling generated type named by another file does not exist there. Whenassembly.CompiledInIsolationis set (onlycodegen testsets it),AddAotRootsleaves out the by-name roots that don't resolve to a type of the same assembly; roots to existingTypes and to the file's own generated types are kept. That compile is never written to disk, socodegen writestill emits every root. See wolverine#4486.- Deciding which types to root is the consuming framework's call — see jasperfx#743 and wolverine#4287.
Verification
The published binary should run with no AOT-specific warnings on the console:
./publish/MyApp
# (no warnings about "Generated native code might not be available at runtime")For a smoke-level confidence check, JasperFx's repo includes src/JasperFx.AotSmoke — a tiny app that consumes the AOT-clean cross-section of the JasperFx + JasperFx.Events surface with all the IL warning codes promoted to errors. Mirroring its pattern in your own repo is a good way to catch regressions early.
What's annotated vs. AOT-clean
AOT-clean (no annotation; safe in AOT publishes)
JasperFx.Events.Event.For<T>(T)— generic event factory.JasperFx.Core.Reflection.GenericFactoryCache.BuildAs<T>(…)when you supply your own delegate factory that avoidsMakeGenericType+Activator.CreateInstance. The default factory does use those and carries[RequiresDynamicCode]; consumers source-generate the per-type factory and stay clean.- Pure utility surface in
JasperFx.Core(string helpers,LightweightCache, etc.). JasperFx.Events.Tags.TagTypeRegistration.FromUnwrapper<TTag, TInner>(unwrapper, tableSuffix)(JasperFx.Events 2.90.0+) — a DCB tag type registered with an explicit unwrapper.TInnermust be a primitive your store's tag table can hold (Guid,string,int,long); it is not validated here, so a wrong choice fails when the store builds the tag table.Create<TTag>()discovers the inner type throughValueTypeInfoand closesTagTypeRegistration<,>withMakeGenericType, which has no native code when the image lacks that instantiation; namingTInnercloses it at compile time.
Annotated (RUC / RDC; available in dev, warns at AOT publish)
- All of
JasperFx.CommandLine—CommandFactory,CommandExecutor,CommandLineHostingExtensions. The annotations stay because the reflective fallback is still there for assemblies built withoutJasperFx.SourceGenerator; an attribute cannot tell whether the generator ran. With the generator wired in, the command line does run in an AOT binary and the call site can be suppressed: see Running the command line in an AOT binary. TypeRepository/AssemblyFinder/AssemblyTypes— assembly scanning is fundamentally trim-hostile. Command discovery and extension/option discovery route around it via theDiscoveredCommandsandDiscoveredExtensionsmanifests.JasperFx.Core.IoCconvention-based registration (AssemblyScanner.Scan,IRegistrationConventionimpls). AOT consumers use explicitservices.AddSingleton<TService, TImpl>()registrations.JasperFx.Core.Reflection.LambdaBuilder+ValueTypeInfo— member accessors and value-type wrappers compiled from expression trees with FastExpressionCompiler under the JIT. Where dynamic code isn't supported they fall back to a reflective path instead of failing, so they run in an AOT binary, just more slowly. Projection dispatch doesn't use them at all: it is entirely source-generated (see Projection Apply Dispatch).JasperFx.CodeGeneration.GeneratedType/GeneratedAssembly/MethodCall— the codegen builder API. Reached only at codegen-write time, not at production startup in Static mode.OptionsDescription— diagnostic reflection over runtime types for thedescribecommand.JasperFx.Events.Tags.TagTypeRegistration.Create<TTag>()(JasperFx.Events 2.90.0+; suppressed before) — discovers a DCB tag's inner type throughValueTypeInfoand closesTagTypeRegistration<,>withMakeGenericType. A store'sRegisterTagType<TTag>()that calls it carries the warning to your call site; register with an explicit unwrapper throughFromUnwrapper<TTag, TInner>instead.
Source-generated command manifest
JasperFx.SourceGenerator emits a JasperFx.Generated.DiscoveredCommands class into every assembly that declares JasperFx commands. Alongside the list of command types it emits a [ModuleInitializer] that registers, as ordinary code the trimmer can see:
- each command type, with a
new T()factory when it has an accessible parameterless constructor; - a
new T()factory for each command's input type; - for a command with
[InjectService]properties, a delegate that sets them from the application's services.
CommandFactory.RegisterCommands(assembly), which RegisterCommandsFromExtensionAssemblies calls for each [JasperFxAssembly] assembly, reads that registration first. Only an assembly built without the generator falls back to scanning its exported types, creating commands with Activator.CreateInstance and finding [InjectService] properties with Type.GetProperties(). None of those three works in a Native AOT image. JasperFx and JasperFx.Events ship built with the generator; reference it in your own app for your app's commands:
<ItemGroup>
<PackageReference Include="JasperFx.SourceGenerator" Version="$(JasperFxVersion)"
PrivateAssets="all" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>The same generator emits a source-generated input parser for each command's input type, so command-line parsing needs no reflection either.
Running the command line in an AOT binary
codegen write is still a dev-time job: it needs Roslyn, so run it with dotnet run before you publish. But an app that ends in RunJasperFxCommands goes through the command line on every start, since run is the default command, and the rest of the commands (check-env, describe, resources, projections, help, your own) are as useful from the published binary as they are in development. With JasperFx.SourceGenerator referenced, they work from a Native AOT binary:
using System.Diagnostics.CodeAnalysis;
using JasperFx;
using JasperFx.CodeGeneration;
public static class Program
{
// ApplyJasperFxExtensions and RunJasperFxCommands keep [RequiresUnreferencedCode] and
// [RequiresDynamicCode] for assemblies built without JasperFx.SourceGenerator. With the generator
// in every assembly that contributes commands, suppress them here.
[UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode",
Justification = "JasperFx.SourceGenerator registers the commands, their factories and their input parsers.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode",
Justification = "Every command input has a source-generated parser.")]
public static async Task<int> Main(string[] args)
{
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.CritterStackDefaults(opts =>
{
opts.Production.GeneratedCodeMode = TypeLoadMode.Static;
opts.Development.GeneratedCodeMode = TypeLoadMode.Dynamic;
});
builder.Host.ApplyJasperFxExtensions();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
return await app.RunJasperFxCommands(args);
}
}A top-level Program.cs has nowhere to put the attributes, which is why this is written as an explicit Main.
Notes:
- The warnings still appear on the call sites without the suppression. That is expected and does not mean the generator is missing; it means the analyzer cannot see it.
- Every assembly that contributes commands must be built with the generator. A command from an assembly without it is found by scanning, which in a Native AOT image finds nothing, so that command is missing from
helprather than failing loudly. ApplyJasperFxExtensionsalso creates the extension type an assembly names in[JasperFxAssembly(typeof(...))]withActivator.CreateInstance. That constructor survives trimming only if something else keeps it.- JasperFx's CI publishes
src/JasperFx.AotCliSmoke, an app shaped like the one above, with Native AOT on every pull request, and runshelp,help <command>, an application command with[InjectService],check-env,describeandrunfrom the native binary (jasperfx#1141).
Source-generated extension manifest
The same generator package emits a companion JasperFx.Generated.DiscoveredExtensions class that lists the assembly's extension / option types at compile time, so consuming frameworks (Wolverine, Marten, …) can register or apply their extensions without the reflective, filesystem-probing assembly scan (AssemblyFinder.FindAssemblies).
A type is discovered when, in an eligible assembly, it is either:
- declared by the assembly's
[JasperFxAssembly]-derived attribute — the generic argument of a[WolverineModule<T>]-style attribute, or atypeof(...)argument to[JasperFxAssembly(typeof(T))]; or - a concrete class implementing the
JasperFx.IJasperFxExtensionmarker interface (whichIServiceRegistrations, and framework interfaces such as Wolverine'sIWolverineExtension, extend).
An assembly is eligible if it carries a [JasperFxAssembly]-derived attribute or is an executable (entry) assembly — matching the assemblies the runtime scanner would otherwise consider. The two sources are de-duplicated.
At runtime, JasperFx.GeneratedExtensionManifest aggregates these manifests across the loaded assemblies:
// All compile-time-discovered extension types, then filter by your framework's interface:
var extensions = GeneratedExtensionManifest
.ReadFromLoadedAssemblies()
.Where(t => typeof(IWolverineExtension).IsAssignableFrom(t));
// AnyManifestPresent() lets a consumer fall back to reflective scanning
// when the generator isn't referenced (no behavior change for non-AOT apps).Enable it with the same JasperFx.SourceGenerator package reference shown above; no separate package is required.
Across the Critter Stack
| Package | AOT posture |
|---|---|
| JasperFx, JasperFx.Events | IsAotCompatible=true. The reflective surface listed above is annotated, and everything else is AOT-clean |
| JasperFx.RuntimeCompiler | Annotated [RequiresDynamicCode] + [RequiresUnreferencedCode] at the class level, and intentionally absent from production publishes |
| Marten, Polecat, Fisher | Pre-generate with dotnet run -- codegen write and run in TypeLoadMode.Static. Projection dispatch comes from the source generator, so it needs no runtime code generation |
| Wolverine | The same pattern: pre-generated handlers and Static mode. Runtime code generation stays an opt-in seam, deliberately not replaced by source generators |
Check each product's own documentation for its current annotation status.
Known limitations
- Wolverine middleware that uses runtime reflection over handler types reflects in a way that can't be source-generated. Stick with the pre-generated codegen path for handler dispatch and you stay clean.
- STJ without a generation context is the most common AOT warning source in real apps. If you serialize your own types via the default
JsonSerializer.Deserialize<T>(string)etc., you'll see IL2026 / IL3050 warnings. The fix is to register aJsonSerializerContextsource-generated context. - First-time codegen output: the
codegen writecommand requires a runningHost, which in turn requires the runtime services for your app. Make sure your app actually starts (e.g. connection strings are valid) at the time you run it. Otherwise you'll see the error from your dependency, not from codegen. - CI-time publish: AOT publish takes meaningfully longer than a JIT-mode publish (typically 30-90 seconds vs. a few seconds). Budget for it in your build pipeline.
References
- CLI: codegen Command — the dev-time codegen tooling this guide builds on
- Migration Guide — broader 1.x → 2.0 context for AOT
- .NET trim warning reference — Microsoft's catalog of IL warning codes
- .NET Native AOT documentation — official Microsoft guide
