Skip to content
Skills Library
Programming · Learning & explanation

orchardcore-source-generators

/orchardcore-source-generators

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 proxies, the OCSG001 analyzer for sealed shape models, the OCSG002 analyzer for FeatureAttribute targets outside the current module, migration from anonymous to named types, and performance optimization. Use this skill when requests mention Orchard Core Source Generators, [GenerateArguments], What G

Licence
MIT
Last repository change
21.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

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 proxies, the OCSG001 analyzer for sealed shape models, the OCSG002 analyzer for FeatureAttribute targets outside the current module, migration from anonymous to named types, and performance optimization. Use this skill when requests mention Orchard Core Source Generators, [GenerateArguments], What G

Original author description

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 proxies, the OCSG001 analyzer for sealed shape models, the OCSG002 analyzer for FeatureAttribute targets outside the current module, migration from anonymous to named types, and performance optimization. Use this skill when requests mention Orchard Core Source Generators, [GenerateArguments], What G

How it works

  1. Use Source Generators for Performance Optimization
Original SKILL.md headings · 304 lines, 1,314 words
SKILL.md preview
---
name: orchardcore-source-generators
description: 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 proxies, the OCSG001 analyzer for sealed shape models, the OCSG002 analyzer for FeatureAttribute targets outside the current module, migration from anonymous to named types, and performance optimization. Use this skill when requests mention Orchard Core Source Generators, [GenerateArguments], What Gets Generated, OCSG001, OCSG002, sealed view model warning, Feature attribute ignored, or closely related Orchard Core troubleshooting work. Strong matches include OrchardCore.SourceGenerators, OrchardCore.DisplayManagement, INamedEnumerable, [GenerateShape], FeatureAttribute, RequireFeatures, Initialize, CreateAsync.
license: Apache-2.0
metadata:
  author: CrestApps Team
  version: "1.0"
---

# 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

- Use `[GenerateArguments]` on `partial` classes to generate optimized `INamedEnumerable<object>` implementations at compile time.
- Generated classes extend `PropertyBasedNamedEnumerable` with zero-reflection property access via switch expressions.
- Classes marked with `[GenerateArguments]` must be `partial` and have at least one public instance property with a getter.
- For .NET 9+ projects, anonymous types passed to `Arguments.From()` are automatically optimized by interceptors.
- On older .NET versions, `Arguments.From()` falls back to cached reflection (acceptable for infrequent usage).
- Prefer named types with `[GenerateArguments]` for production code over anonymous types.
- Source-generated argument classes support nested types, records, and inheritance.
- `OrchardCore.SourceGenerators` ships as an analyzer with the Orchard Core packages; no extra reference is needed in modules built on `OrchardCore.Module.Targets`.
- Shape **view models** used with `Initialize<TModel>()` or proxy-based `CreateAsync<TModel>()` must not be `sealed` (`OCSG001`), unless they implement `IShape`.
- `[Feature("...")]` on a type must name a feature declared by the same module (`OCSG002`); use `[RequireFeatures("...")]` for other modules' features.
- All other C# classes must use the `sealed` modifier where applicable.

### Quick Start with [GenerateArguments]

```csharp
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`:

```csharp
// 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]

- **No reflection** — Direct property access via switch expressions.
- **Compile-time code generation** — Errors caught at build time.
- **Lazy evaluation** — Properties accessed on-demand.
- **Type safety** — Strongly typed arguments with IntelliSense.
- **Minimal allocation** — No intermediate dictionaries until accessed.

### Real-World Examples

#### Pager Shape Arguments

```csharp
[GenerateArguments]
public partial class PagerSlim
{
    public int PageSize { get; set; }
    public string Before { get; set; }
    public string After { get; set; }
}
```

#### Content Zone Arguments

```csharp
[GenerateArguments]
internal sealed partial class ContentZoneArguments
{
    public string Identifier { get; set; }
}
```

#### Navigation Arguments

```csharp
[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:

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

**Requirements:**
- .NET 9.0 or later
- C# 13 or later

**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:

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

### Migration from Anonymous Types to Named Types

```csharp
// 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

- **Better IntelliSense** — Strongly typed with autocomplete.
- **Compile-time safety** — Typos caught at build time.
- **Reusability** — Named types shared across multiple shapes.
- **Testability** — Easier to unit test.
- **Zero reflection** — Direct property access.

### Advanced: Nested Types

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

### Advanced: Records

```csharp
[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

```csharp
// 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.

```csharp
// 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:

```csharp
using OrchardCore.DisplayManagement;

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

    public double Temperature { get; set; }
}
```

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:

```csharp
// 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`:**

```csharp
// 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.

Versions

The database has no other skills named orchardcore-source-generators.

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version 1d4c01b5a7fb (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100orchardcore-graphql
    Skill for configuring and using the GraphQL API in Orchard Core. Covers GraphQL queries, custom graph types, content querying, IIndexAliasProvider, AddWhereInputIndexPropertyProvider, where filters, GraphQLPermissions, named query permissions, RequirePermission on fields, the…
  • 100orchardcore-twitter
    Skill for integrating X Twitter in Orchard Core. Covers TwitterClient, X API settings, sign in with X Twitter, TwitterSettings, TwitterSigninSettings, ConfigureTwitterSettings with the OrchardCore X configuration section, ConsumerSecret and AccessTokenSecret from configuration…
  • 100generators-cheatsheet
    USE FOR: Building incremental source generators that emit C# code at compile time, including syntax providers, semantic model queries, attribute-driven generation, and diagnostic reporting. DO NOT USE FOR: IL weaving (use Fody), T4 text templates, runtime code generation with…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.