Dotnet Aot Architecture logo

Dotnet Aot Architecture

Community
wshaddix
dotnet-aot-architecture

Designing AOT-first apps. Source gen over reflection, AOT-safe DI, serialization, factories.

Overview

Publisherwshaddix
Repositorydotnet-skills
Skill namedotnet-aot-architecture
Stars
79
Forks
13
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by wshaddix on GitHub. Read the source before you install it.

Installation

Install the Dotnet Aot Architecture AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wshaddix/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/skills/dotnet-aot-architecture .claude/skills/dotnet-aot-architecture
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Dotnet Aot Architecture in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Dotnet Aot Architecture on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Dotnet Aot Architecture is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

dotnet-aot-architecture

AOT-first application design patterns for .NET 8+: preferring source generators over reflection, explicit DI registration over assembly scanning, AOT-safe serialization choices, library compatibility assessment, and factory patterns replacing Activator.CreateInstance.

Version assumptions: .NET 8.0+ baseline. Patterns apply to all AOT-capable project types (console, ASP.NET Core Minimal APIs, worker services).

Out of scope: Native AOT publish pipeline and MSBuild configuration -- see [skill:dotnet-native-aot]. Trim-safe library authoring and annotations -- see [skill:dotnet-trimming]. WASM AOT compilation -- see [skill:dotnet-aot-wasm]. MAUI-specific AOT -- see [skill:dotnet-maui-aot]. Source generator authoring (Roslyn API) -- see [skill:dotnet-csharp-source-generators]. DI container internals -- see [skill:dotnet-csharp-dependency-injection]. Serialization depth -- see [skill:dotnet-serialization].

Cross-references: [skill:dotnet-native-aot] for the AOT publish pipeline, [skill:dotnet-trimming] for trim annotations and library authoring, [skill:dotnet-serialization] for serialization patterns, [skill:dotnet-csharp-source-generators] for source gen mechanics, [skill:dotnet-csharp-dependency-injection] for DI fundamentals, [skill:dotnet-containers] for runtime-deps deployment, [skill:dotnet-native-interop] for general P/Invoke patterns and marshalling.


Source Generators Over Reflection

The primary AOT enabler is replacing runtime reflection with compile-time source generation. Source generators produce code at build time that the AOT compiler can analyze and include.

Key Source Generator Replacements

Reflection PatternSource Generator / AOT-Safe AlternativeLibrary
JsonSerializer.Deserialize<T>()[JsonSerializable] contextSystem.Text.Json (built-in)
Activator.CreateInstance<T>()Factory pattern with explicit newManual
Type.GetProperties() for mapping[Mapper] attributeMapperly
Regex pattern compilation[GeneratedRegex] attributeBuilt-in (.NET 7+)
ILogger.Log(...) with string interpolation[LoggerMessage] attributeMicrosoft.Extensions.Logging
Assembly scanning for DIExplicit services.Add*()Manual
[DllImport] P/Invoke[LibraryImport]Built-in (.NET 7+)
AutoMapper CreateMap<>()[Mapper] source genMapperly

Example: Migrating to Source Gen

csharp
// BEFORE: Reflection-based (breaks under AOT)
var logger = loggerFactory.CreateLogger<OrderService>();
logger.LogInformation("Order {OrderId} created for {Customer}", order.Id, order.CustomerId);

// AFTER: Source-generated (AOT-safe, zero-alloc)
public partial class OrderService
{
    [LoggerMessage(Level = LogLevel.Information,
        Message = "Order {OrderId} created for {Customer}")]
    private static partial void LogOrderCreated(
        ILogger logger, int orderId, string customer);
}

// Usage:
LogOrderCreated(_logger, order.Id, order.CustomerId);

See [skill:dotnet-csharp-source-generators] for source generator mechanics and authoring patterns.


AOT-Safe DI Patterns

Dependency injection in AOT requires explicit service registration. Assembly scanning (AddServicesFromAssembly) and open-generic resolution may require reflection that AOT cannot satisfy.

Explicit Registration (Preferred)

csharp
var builder = WebApplication.CreateSlimBuilder(args);

// Explicit registrations -- AOT-safe
builder.Services.AddSingleton<IOrderRepository, PostgresOrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
builder.Services.AddSingleton(TimeProvider.System);

Avoid Assembly Scanning

csharp
// BAD: Assembly scanning uses reflection -- breaks under AOT
builder.Services.Scan(scan => scan
    .FromAssemblyOf<OrderService>()
    .AddClasses(classes => classes.AssignableTo<IService>())
    .AsImplementedInterfaces()
    .WithScopedLifetime());

// GOOD: Explicit registrations grouped by concern
builder.Services.AddOrderServices();
builder.Services.AddInventoryServices();

// Extension method groups related registrations
public static class OrderServiceExtensions
{
    public static IServiceCollection AddOrderServices(
        this IServiceCollection services)
    {
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<IOrderRepository, PostgresOrderRepository>();
        services.AddScoped<IOrderValidator, OrderValidator>();
        return services;
    }
}

Keyed Services (.NET 8+)

csharp
// AOT-safe keyed service registration
builder.Services.AddKeyedSingleton<INotificationSender, EmailSender>("email");
builder.Services.AddKeyedSingleton<INotificationSender, SmsSender>("sms");

// Resolve by key
app.MapPost("/notify", ([FromKeyedServices("email")] INotificationSender sender) =>
    sender.SendAsync("Hello"));

See [skill:dotnet-csharp-dependency-injection] for full DI patterns.


Serialization Choices for AOT

Decision Matrix

SerializerAOT-SafeSetup RequiredBest For
System.Text.Json + source genYes[JsonSerializable] contextAPIs, config, JSON interop
Protobuf (Google.Protobuf)Yes.proto schema filesgRPC, service-to-service
MessagePack + source genYes[MessagePackObject] + source gen resolverCaching, real-time
Newtonsoft.JsonNoN/ADo not use for AOT
STJ without source genNoN/AFalls back to reflection

STJ Source Gen Setup

csharp
// Define serializable types
[JsonSerializable(typeof(Product))]
[JsonSerializable(typeof(List<Product>))]
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal partial class AppJsonContext : JsonSerializerContext { }

// Register in ASP.NET Core
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0,
        AppJsonContext.Default);
});

See [skill:dotnet-serialization] for comprehensive serialization patterns.


Factory Patterns Replacing Activator.CreateInstance

Activator.CreateInstance uses runtime reflection to create instances and is incompatible with AOT. Replace with factory patterns that use explicit construction.

Simple Factory

csharp
// BAD: Reflection-based creation -- breaks under AOT
public T CreateHandler<T>() where T : class
    => (T)Activator.CreateInstance(typeof(T))!;

// GOOD: Factory with explicit registration
public class HandlerFactory
{
    private readonly Dictionary<Type, Func<IHandler>> _factories = new();

    public void Register<T>(Func<T> factory) where T : IHandler
        => _factories[typeof(T)] = () => factory();

    public IHandler Create<T>() where T : IHandler
        => _factories[typeof(T)]();
}

// Registration
var factory = new HandlerFactory();
factory.Register<OrderHandler>(() => new OrderHandler(repository, logger));
factory.Register<PaymentHandler>(() => new PaymentHandler(gateway));

Strategy Pattern via DI

csharp
// BAD: Dynamic type resolution
public IPaymentProcessor GetProcessor(string type)
{
    var processorType = Type.GetType($"MyApp.Payments.{type}Processor");
    return (IPaymentProcessor)Activator.CreateInstance(processorType!)!;
}

// GOOD: Keyed services (.NET 8+)
builder.Services.AddKeyedScoped<IPaymentProcessor, CreditCardProcessor>("CreditCard");
builder.Services.AddKeyedScoped<IPaymentProcessor, BankTransferProcessor>("BankTransfer");
builder.Services.AddKeyedScoped<IPaymentProcessor, WalletProcessor>("Wallet");

// Resolve at runtime without reflection
app.MapPost("/pay", (
    [FromQuery] string type,
    IServiceProvider sp) =>
{
    var processor = sp.GetRequiredKeyedService<IPaymentProcessor>(type);
    return processor.ProcessAsync();
});

Enum-Based Factory

csharp
// For a fixed set of types, use a switch expression
public static IExporter CreateExporter(ExportFormat format) => format switch
{
    ExportFormat.Csv => new CsvExporter(),
    ExportFormat.Json => new JsonExporter(),
    ExportFormat.Pdf => new PdfExporter(),
    _ => throw new ArgumentOutOfRangeException(nameof(format))
};

Library Compatibility Assessment

Assessment Checklist

Before adopting a NuGet package in an AOT project:

  1. Check for IsAotCompatible in the package source -- packages that set this are validated against AOT analyzers
  2. Check for [RequiresDynamicCode] / [RequiresUnreferencedCode] annotations -- these indicate AOT-incompatible APIs
  3. Run AOT analyzers against your usage -- dotnet build /p:EnableAotAnalyzer=true
  4. Check the package's GitHub issues for AOT/trimming reports -- search for "Native AOT", "trimming", "IL2026", "IL3050"
  5. Look for source-generated alternatives -- many reflection-based libraries now have source-gen companions

Common Library Status

LibraryAOT StatusAOT-Safe Alternative
AutoMapperBreaksMapperly
MediatRPartial (explicit registration)Direct method calls or factory
FluentValidationPartialManual validation or source gen
DapperCompatible (.NET 8+ AOT support)--
Entity Framework CorePartial (precompiled queries)Dapper for AOT-heavy paths
RefitCompatible (7+ with source gen)--
PollyCompatible (v8+)--
SerilogPartial[LoggerMessage] source gen
HangfireBreaksCustom IHostedService

Testing Compatibility

bash
# Build with all analyzers enabled
dotnet build /p:EnableAotAnalyzer=true /p:EnableTrimAnalyzer=true /p:TrimmerSingleWarn=false

# Warnings indicate AOT-incompatible usage
# IL3050 = RequiresDynamicCode (definitely breaks)
# IL2026 = RequiresUnreferencedCode (may break)

AOT Application Architecture Template

src/
  MyApp/
    Program.cs                   # CreateSlimBuilder, explicit DI
    MyApp.csproj                 # PublishAot=true, EnableAotAnalyzer=true
    JsonContext.cs               # [JsonSerializable] for all API types
    Endpoints/
      OrderEndpoints.cs          # Minimal API route groups
      ProductEndpoints.cs
    Services/
      OrderService.cs            # Business logic (no reflection)
      IOrderService.cs
    Repositories/
      OrderRepository.cs         # Data access (Dapper or EF precompiled)
    Extensions/
      ServiceCollectionExtensions.cs  # Grouped DI registrations

Agent Gotchas

  1. Do not use Activator.CreateInstance in AOT projects. It requires runtime reflection that is not available. Use factory patterns, DI keyed services, or switch expressions instead.
  2. Do not use assembly scanning for DI registration (Scan, RegisterAssemblyTypes, FromAssemblyOf). These use reflection to discover types at runtime. Register services explicitly.
  3. Do not use System.Text.Json without a [JsonSerializable] context in AOT. Without a source-generated context, STJ falls back to reflection and fails at runtime.
  4. Do not assume a library is AOT-compatible without testing. Run dotnet build /p:EnableAotAnalyzer=true and check for IL3050/IL2026 warnings against your specific usage.
  5. Do not use Type.GetType() or Assembly.GetTypes() for runtime discovery. These rely on metadata that may be trimmed. Use compile-time known types.

References

Frequently asked questions

What does the Dotnet Aot Architecture AI skill do?

Designing AOT-first apps. Source gen over reflection, AOT-safe DI, serialization, factories.

Why use Dotnet Aot Architecture on TypingMind?

Because you install it once and use it with any model. Dotnet Aot Architecture is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Dotnet Aot Architecture in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wshaddix/dotnet-skills/tree/master/skills/dotnet-aot-architecture. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Dotnet Aot Architecture?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Dotnet Aot Architecture?

As many as you like. As long as a model supports skills, you can use Dotnet Aot Architecture with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Dotnet Aot Architecture AI skill free?

It is published on GitHub by wshaddix. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇