Orchardcore source generators

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore source generators is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for using Orchard Core source generators and build-time analyzers. Covers the GenerateArguments attribute for compile-time named argument types, anonymous type interceptors for .NET 9+, PropertyBasedNamedEnumerable, the GenerateShape attribute and shape factory interceptors that avoid runtime

How to use this skill

Skill file

Orchard Core Source Generators - Prompt Templates

Use Source Generators for Performance Optimization

You are an Orchard Core expert. Generate code using source generators, the [GenerateArguments] attribute, anonymous type interceptors, and named argument types for shapes and display management.

Guidelines

Quick Start with [GenerateArguments]

using OrchardCore.DisplayManagement;

[GenerateArguments]
public sealed partial class MyShapeArguments
{
    public string Title { get; set; }
    public int Count { get; set; }
    public bool IsActive { get; set; }
}

// Usage - direct property access, no reflection
var args = new MyShapeArguments
{
    Title = "Hello",
    Count = 42,
    IsActive = true,
};

var shape = await shapeFactory.CreateAsync("MyShape", args);

What Gets Generated

The source generator produces an optimized implementation extending PropertyBasedNamedEnumerable:

// Your code:
[GenerateArguments]
public sealed partial class MyData
{
    public string Name { get; set; }
    public int Value { get; set; }
}

// Auto-generated at compile time:
public sealed partial class MyData : PropertyBasedNamedEnumerable
{
    private static readonly string[] s_propertyNames = ["Name", "Value"];

    protected override int PropertyCount => 2;

    protected override IReadOnlyList<string> PropertyNames => s_propertyNames;

    protected override object? GetPropertyValue(int index) => index switch
    {
        0 => this.Name,
        1 => this.Value,
        _ => throw new ArgumentOutOfRangeException(nameof(index))
    };
}

Benefits of [GenerateArguments]

Real-World Examples

Pager Shape Arguments
[GenerateArguments]
public partial class PagerSlim
{
    public int PageSize { get; set; }
    public string Before { get; set; }
    public string After { get; set; }
}
Content Zone Arguments
[GenerateArguments]
internal sealed partial class ContentZoneArguments
{
    public string Identifier { get; set; }
}
Navigation Arguments
[GenerateArguments]
internal sealed partial class NavigationArguments
{
    public string MenuName { get; set; }
    public string RouteUrl { get; set; }
}

Anonymous Type Interceptors (.NET 9+)

For .NET 9+ projects, anonymous types are automatically optimized using C# interceptors with no code changes:

// Automatically optimized at compile time
var shape = await factory.CreateAsync("MyShape", new
{
    Title = "Hello",
    Count = 42,
});

Requirements:

Orchard Core 4.0 projects target net11.0, which meets both requirements.

How it works: The interceptor detects Arguments.From(anonymousType) calls and generates optimized code using type inference to cast to the actual anonymous type, eliminating reflection and dynamic overhead.

Fallback: Reflection with Caching

On older .NET versions, Arguments.From() uses cached reflection:

// Works on any .NET version - uses reflection + caching
var args = Arguments.From(new { Title = "Test", Count = 5 });

Migration from Anonymous Types to Named Types

// Before (anonymous type):
var shape = await factory.CreateAsync("MyShape", new
{
    Title = "Hello",
    Count = 5,
});

// After (recommended named type):
[GenerateArguments]
public sealed partial class MyShapeArguments
{
    public string Title { get; set; }
    public int Count { get; set; }
}

var args = new MyShapeArguments { Title = "Hello", Count = 5 };
var shape = await factory.CreateAsync("MyShape", args);

Migration Benefits

Advanced: Nested Types

public sealed partial class OuterClass
{
    [GenerateArguments]
    public sealed partial class InnerArguments
    {
        public string Value { get; set; }
    }
}

Advanced: Records

[GenerateArguments]
public sealed partial record MyRecordArgs(string Title, int Count);

Decision Guide

Production code with reusable types?
├─ Yes → Use [GenerateArguments] ✅ RECOMMENDED
└─ No
   └─ Using .NET 9+ with anonymous types?
      ├─ Yes → Interceptors (automatic) ✅
      └─ No → Reflection with caching (acceptable for rare usage)

Build-Time Analyzers

| Rule | Severity | Reported when | Fix |

|------|----------|---------------|-----|

| OCSG001 | Warning | A sealed type that does not implement IShape is passed to a proxy-based shape API such as Initialize<TModel>() or CreateAsync<TModel>() | Remove sealed, implement IShape, or use View(), Copy() or Dynamic() |

| OCSG002 (4.0) | Warning | OrchardCore.Modules.FeatureAttribute targets a feature ID not declared by the current module assembly | Use a local feature ID, or [RequireFeatures(...)] for another module's feature |

OCSG001
// warning OCSG001: Type 'DebugSettingsViewModel' is sealed and does not implement IShape ...
public sealed class DebugSettingsViewModel
{
    public bool WriteShapeDebugInformation { get; set; }
}

// Fix: view models stay unsealed.
public class DebugSettingsViewModel
{
    public bool WriteShapeDebugInformation { get; set; }
}
OCSG002

Orchard Core resolves [Feature] targets only against the features of the same assembly. A cross-module ID is silently ignored and the type falls back to the module's default feature mapping, so the startup runs when you did not expect it.

// warning OCSG002: Feature 'OrchardCore.Liquid' is not defined by the current module 'MyModule', so OrchardCore will ignore this target.
[Feature("OrchardCore.Liquid")]
public sealed class LiquidStartup : StartupBase { }

// Fix: depend on the other module's feature.
[RequireFeatures("OrchardCore.Liquid")]
public sealed class LiquidStartup : StartupBase { }

Shape Model Generation (`[GenerateShape]`)

Proxy-based shapes (Initialize<TModel>()) normally subclass the model at runtime with Castle DynamicProxy. The shape factory generator intercepts these calls at compile time for non-abstract classes with an accessible parameterless constructor and generates the derived shape type instead, so no runtime proxy is built. Sealed models still cannot be derived from (OCSG001).

To make the model itself the shape, mark a partial class with [GenerateShape]; the generator implements IShape and IPositioned on it:

using OrchardCore.DisplayManagement;

[GenerateShape]
public partial class WeatherWidgetViewModel
{
    public string City { get; set; }

    public double Temperature { get; set; }
}

Generated shape types are named GeneratedShape_<hash>, where the hash covers the identity of the consuming assembly and the model's full name. Each assembly that calls Initialize<TModel>() or CreateAsync<TModel>() on a model of a shared library gets its own public wrapper type, so two assemblies generating wrappers for the same model no longer collide (CS0436). Never reference a GeneratedShape_* type by name: it changes with the assembly.

This generator is newer than the published docs; inspect the generated files under obj/<Configuration>/<TargetFramework>/generated/OrchardCore.SourceGenerators/ when troubleshooting.

Troubleshooting

"Type must be partial" — Add the partial keyword:

// Correct
[GenerateArguments]
public sealed partial class MyData { }

// Wrong - will not compile
[GenerateArguments]
public sealed class MyData { }

Generated code not found:

  1. Rebuild the project
  2. Check obj/<Configuration>/<TargetFramework>/generated/ for generated files
  3. Restart Visual Studio if needed

Do not manually cast to INamedEnumerable:

// Correct - pass arguments directly
var args = new MyShapeArguments { Title = "Test" };
var shape = await factory.CreateAsync("MyShape", args);

// Wrong - unnecessary manual cast
var enumerable = (INamedEnumerable<object>)args;

Best Practices

  1. Use [GenerateArguments] for all production shape arguments.
  2. Use descriptive class names (e.g., UserProfileShapeArgs over Args).
  3. Group related properties into focused models.
  4. Keep property counts reasonable (2-20 properties).
  5. Add XML comments to document the model's purpose.
  6. Avoid complex logic in property getters.
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.