Skip to content

[Blazor] Generate framework component metadata - #68300

Open
javiercn wants to merge 5 commits into
javiercn-component-metadata-aotfrom
javiercn-framework-component-metadata
Open

javiercn wants to merge 5 commits into
javiercn-component-metadata-aotfrom
javiercn-framework-component-metadata

Conversation

@javiercn

@javiercn javiercn commented Aug 9, 2026 •

Copy link
Copy Markdown
Member

Overview

This is layer 5 of 6 for the Aspire Dashboard Native AOT feature, stacked on #68299. Across five commits and 23 files, it teaches the Razor components metadata generator to import component descriptions from the framework assemblies that own those components, then adds providers for Components, Web, Forms, Endpoints, Authorization, QuickGrid, Media, and WebAssembly Authentication. The governing constraint is that application metadata and framework-owner metadata must compose without reflection, while optional assemblies contribute nothing unless the application actually references them; strict reflection switches and Native AOT execution remain in layer 6. The provider tests use the upstream shared MSTest/MTP Components.Testing harness from #67083 and #68289; this PR adds no duplicate testing infrastructure or xUnit dependency.

Design

There is no new public API. The generator emits an internal, compile-time-only attribute that lets the feature application name closed generic roots which cannot be inferred from an open generic definition:

// src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs
// Internal to the generated compilation: applications do not acquire a new supported API surface.
// AllowMultiple lets one metadata context root every required closed generic family.
context.RegisterPostInitializationOutput(static output =>
    output.AddSource(
        "ComponentTypeInfoAttribute.g.cs",
        """
        namespace Microsoft.AspNetCore.Components.Web
        {
            [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true)]
            internal sealed class ComponentTypeInfoAttribute : global::System.Attribute
            {
                public ComponentTypeInfoAttribute(global::System.Type componentType)
                {
                }
            }
        }
        """));

Each owner assembly implements the same internal convention: a type named Microsoft.AspNetCore.Components.Infrastructure.BuiltInComponentDescriptors exposes GetDescriptors() for fixed components and named generic factory methods for closed families. The application generator deliberately does not duplicate framework internals: owner providers can access private members, required constructors, and internal helper component graphs safely, while the generator carries only the data required to bind to those factories.

// src/Components/Endpoints/gen/Models/MetadataContextModel.cs
// The incremental model keeps assembly/factory identity, concrete type arguments, CLR constraints,
// and DynamicallyAccessedMembers values as immutable data rather than retaining Roslyn symbols.
internal sealed record class BuiltInDescriptorFactoryModel(
    string AssemblyName,
    string MethodName,
    ImmutableArray<string> TypeArgumentFullyQualifiedNames,
    ImmutableArray<string> TypeParameterConstraintClauses,
    ImmutableArray<int> TypeParameterDynamicallyAccessedMemberValues);

This owner-provider design was chosen over application-side reflection or re-describing framework private state. It also preserves package isolation: the known provider list is filtered against the host compilation's referenced assemblies, so Authorization, QuickGrid, Media, and WebAssembly Authentication metadata is imported only when those packages are present. Framework JS callback providers are unchanged and remain owned by the earlier JSInterop layer.

Implementation

The generator starts from the metadata context a consumer already registers. It computes application descriptors once, discovers referenced owner providers, collects implicit and explicitly rooted generic factories, and merges those inputs into the context model:

// src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs
var components = CollectComponents(expanded, types, diagnostics, cancellationToken);
var implicitBuiltInDescriptorFactories = CollectImplicitBuiltInDescriptorFactories(
    expanded,
    types,
    cancellationToken);
var referencedAssemblyNames = new HashSet<string>(
    expanded.SourceModule.ReferencedAssemblySymbols.Select(static assembly => assembly.Identity.Name),
    StringComparer.Ordinal);

// Optional-package isolation: if QuickGrid is not referenced, no QuickGrid provider accessor is emitted.
var builtInDescriptorAssemblies = BuiltInDescriptorAssemblies
    .Where(referencedAssemblyNames.Contains)
    .ToImmutableArray();

var explicitComponents = CollectExplicitComponents(
    contextType,
    expanded,
    types,
    diagnostics,
    cancellationToken);

models.Add(new MetadataContextModel(
    Namespace: contextType.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : null,
    ContainingTypes: GetContainingTypeNames(contextType),
    TypeName: contextType.Name,
    TypeKeyword: contextType.IsRecord ? "record" : "class",
    DeclaresJsonTypeInfoResolver: DeclaresMember(contextType, "JsonTypeInfoResolver"),
    BuiltInDescriptorAssemblies: builtInDescriptorAssemblies,
    BuiltInJSInvokableDescriptorAssemblies: builtInJSInvokableDescriptorAssemblies,
    BuiltInDescriptorFactories: implicitBuiltInDescriptorFactories.AddRange(explicitComponents.Factories),
    Components: components.AddRange(explicitComponents.Components),
    BindableTypes: bindableTypes,
    JSInvokableMethods: jsInvokableMethods));

Emission preserves the lower layer's application descriptors and spreads owner descriptors after them. Both fixed providers and generic factories are linked with generated UnsafeAccessor declarations, so the runtime receives ordinary descriptor arrays with no assembly scanning, MakeGenericType, or reflective member access:

// src/Components/Endpoints/gen/Emitters/RazorComponentsMetadataGenerator.Emitter.cs
writer.WriteLine($"internal static readonly {ComponentDescriptorType}[] Components =");
writer.OpenBracket();

for (var i = 0; i < components.Length; i++)
{
    EmitComponent(writer, components[i], i);
}

for (var i = 0; i < builtInDescriptorAssemblies.Length; i++)
{
    writer.WriteLine($".. GetBuiltInComponentDescriptors_{i}(null),");
}

for (var i = 0; i < builtInDescriptorFactories.Length; i++)
{
    var typeArguments = string.Join(", ", builtInDescriptorFactories[i].TypeArgumentFullyQualifiedNames);
    writer.WriteLine($".. GetBuiltInComponentDescriptorFactory_{i}<{typeArguments}>(null),");
}

writer.CloseBracketWithSemicolon();

// The emitted declaration names the internal provider by assembly-qualified type rather than reflecting.
for (var i = 0; i < builtInDescriptorAssemblies.Length; i++)
{
    writer.WriteLine();
    writer.WriteLine(
        "[global::System.Runtime.CompilerServices.UnsafeAccessor(" +
        "global::System.Runtime.CompilerServices.UnsafeAccessorKind.StaticMethod, Name = \"GetDescriptors\")]");
    writer.WriteLine(
        $"private static extern {ComponentDescriptorType}[] GetBuiltInComponentDescriptors_{i}(" +
        "[global::System.Runtime.CompilerServices.UnsafeAccessorType(" +
        $"{SymbolHelpers.ToStringLiteral($"{BuiltInDescriptorProviderType}, {builtInDescriptorAssemblies[i]}")})] object? target);");
}

A fixed owner inventory is represented by Components' Router: the provider owns activation, every parameter, and injections whose setters are private. Web, Forms, and Endpoints use the same pattern for their non-generic inventories.

// src/Components/Components/src/Infrastructure/BuiltInComponentDescriptors.cs
new ComponentDescriptor
{
    Type = typeof(Router),
    CreateInstance = static _ => new Router(),
    Parameters =
    [
        CreateParameter<Assembly>(
            nameof(Router.AppAssembly),
            static target => target.AppAssembly,
            static (target, value) => target.AppAssembly = value),
        // AdditionalAssemblies, NotFound, Found, navigation callbacks, and layout metadata omitted.
    ],
    Injectables =
    [
        CreateInjectable<NavigationManager>("NavigationManager", SetNavigationManager),
        CreateInjectable<INavigationInterception>("NavigationInterception", SetNavigationInterception),
        CreateInjectable<ILoggerFactory>("LoggerFactory", SetLoggerFactory),
        CreateInjectable<IServiceProvider>("ServiceProvider", SetServiceProvider),
    ],
};

[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "set_NavigationManager")]
private static extern void SetNavigationManager(Router target, NavigationManager value);

The remaining provider behaviors form four equivalence classes; one representative and each delta are shown here:

  • Closed generic factories: Forms inputs, ValidationMessage<T>, Virtualize<T>, OwningComponentBase, QuickGrid families, and RemoteAuthenticatorViewCore<TState> preserve concrete arguments, constraints, and trimming annotations. QuickGrid additionally contributes the internal cascading context and tuple-shaped virtualization helper needed by QuickGrid<T>:
// src/Components/QuickGrid/Microsoft.AspNetCore.Components.QuickGrid/src/Infrastructure/BuiltInComponentDescriptors.cs
internal static ComponentDescriptor[] CreateQuickGridDescriptors<TGridItem>()
    =>
    [
        new ComponentDescriptor
        {
            Type = typeof(QuickGrid<TGridItem>),
            CreateInstance = static _ => new QuickGrid<TGridItem>(),
            Injectables =
            [
                CreateInjectable<QuickGrid<TGridItem>, IServiceProvider>(
                    "Services",
                    QuickGridAccessors<TGridItem>.SetServices),
                CreateInjectable<QuickGrid<TGridItem>, IJSRuntime>(
                    "JS",
                    QuickGridAccessors<TGridItem>.SetJS),
                CreateInjectable<QuickGrid<TGridItem>, NavigationManager>(
                    "NavigationManager",
                    QuickGridAccessors<TGridItem>.SetNavigationManager),
            ],
        },
        new ComponentDescriptor
        {
            Type = typeof(CascadingValue<InternalGridContext<TGridItem>>),
            // ChildContent, Value, Name, and IsFixed parameter descriptors omitted.
        },
        .. VirtualizeDescriptorFactory.CreateDescriptors<(int RowIndex, TGridItem Data)>(null),
    ];

internal static ComponentDescriptor[] CreateColumnBaseDescriptors<
    TGridItem,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TColumn>()
    where TColumn : ColumnBase<TGridItem>
    =>
    [
        new ComponentDescriptor
        {
            Type = typeof(TColumn),
            Parameters =
            [
                CreateCascadingParameter<ColumnBase<TGridItem>, InternalGridContext<TGridItem>>(
                    "InternalGridContext",
                    ColumnBaseAccessors<TGridItem>.GetInternalGridContext,
                    ColumnBaseAccessors<TGridItem>.SetInternalGridContext),
            ],
        },
    ];
  • Private/internal component state: Authorization describes AuthorizeView, AuthorizeRouteView, CascadingAuthenticationState, and the private nested AuthorizeRouteViewCore; owner-side helpers construct the private core while UnsafeAccessor bridges its inherited private parameters and services. QuickGrid and WebAssembly Authentication use the same bridge pattern for private injections.
  • Required construction: Media's Image, Video, and FileDownload cannot use a plain parameterless factory because Source is required. Their owner provider deliberately constructs new Image { Source = null! } (and peers) before normal parameter assignment and supplies the private JS runtime/logger injections.
  • Remote-auth family: RemoteAuthenticatorViewCore<TAuthenticationState> preserves where TAuthenticationState : RemoteAuthenticationState plus the JsonSerialized DAM requirement, and closes all five service types over the same authentication-state type.

The feature application roots representative closed instances beside their optional assembly references, covering generic Forms inputs, virtualization, application generics, QuickGrid's grid/column/notifier graph, and remote authentication:

// src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/SampleMetadata.cs
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.CascadingValue<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.Forms.ValidationMessage<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.Forms.InputDate<DateTime>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.Forms.InputNumber<int>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.QuickGrid.QuickGrid<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.QuickGrid.PropertyColumn<string, string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.QuickGrid.TemplateColumn<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.QuickGrid.Infrastructure.ColumnsCollectedNotifier<string>))]
[ComponentTypeInfo(typeof(global::Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticatorViewCore<global::Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState>))]
internal sealed partial class SampleMetadata : RazorComponentsMetadataContext
{
    // Existing JSON resolver composition is unchanged.
}

Outcome

Equivalence class What the tests prove
Provider selection and composition Only referenced owner assemblies emit accessors; application descriptors remain isolated and compose with owner descriptors; JS callback providers are not part of this change.
Fixed framework inventories Components, Web, Forms, Endpoints, and Authorization expose the exact component/parameter/injection shapes, including route/layout metadata and hidden member round-trips.
Generic factories Forms, virtualization, owning components, QuickGrid, derived custom columns, and remote-auth state families preserve concrete type arguments, constraints, DAM annotations, activation, cascading parameters, and private injections.
Owner-specific deviations Media's required construction succeeds; Authorization's private nested core is constructible; QuickGrid emits its internal helper graph; remote authentication closes all services over a custom state type.
Feature roots The existing feature application compiles explicit representatives for every generic family and carries optional-package references beside their providers. Three focused JIT witnesses cover Forms, generic templates, and virtualization on the upstream shared harness.
Test integration The 68-execution provider descriptor matrix is MSTest-native; the PR contains no xUnit residue and no changes under src/Components/Testing.

Validation: the complete built-in descriptor generator matrix passed 113/113 tests. Fast affected suites across Components, Web, Forms, Endpoints, Authorization, QuickGrid, Media, and WebAssembly Authentication passed 2,784 tests with 8 existing skips. The upstream feature harness built cleanly and its focused JIT smoke passed 3/3 tests. Native AOT execution and strict reflection-disabled validation are intentionally deferred to layer 6.

@javiercn
javiercn force-pushed the javiercn-framework-component-metadata branch from c68b966 to d9a8361 Compare August 9, 2026 11:58
@javiercn
javiercn force-pushed the javiercn-framework-component-metadata branch from d9a8361 to 27ac444 Compare August 9, 2026 12:46
@javiercn
javiercn force-pushed the javiercn-framework-component-metadata branch from 27ac444 to 617eaa6 Compare August 9, 2026 19:34
@javiercn
javiercn force-pushed the javiercn-framework-component-metadata branch from 617eaa6 to 58a0cfe Compare August 9, 2026 21:54
javiercn and others added 5 commits August 11, 2026 12:54
Discover framework-owned component assemblies and merge their owner descriptors with application metadata. Add generic factory imports and generated UnsafeAccessors for Components, Web, Forms, and Endpoints.

Co-authored-by: Copilot App <[email protected]>
Cover core provider imports, explicit closed generic roots, owner factory selection, and provider-aware generator diagnostics while retaining application descriptor isolation.

Co-authored-by: Copilot App <[email protected]>
Add owner descriptors for Authorization, QuickGrid, Media, and WebAssembly Authentication, including constrained generic factories, private injection bridges, and required construction paths.

Co-authored-by: Copilot App <[email protected]>
Exercise the complete built-in component descriptor matrix, including constrained QuickGrid factories, private injectable bridges, Media construction, and remote authentication component families. Framework JS callback coverage remains in its lower stack layer.

Co-authored-by: Copilot App <[email protected]>
Reference optional framework packages beside their owner providers and root representative closed generic components for Forms, virtualization, QuickGrid, and remote authentication in the existing JIT feature harness.

Co-authored-by: Copilot App <[email protected]>
@javiercn
javiercn force-pushed the javiercn-framework-component-metadata branch from 58a0cfe to 7a7e46c Compare August 11, 2026 11:31
@javiercn
javiercn marked this pull request as ready for review August 11, 2026 14:07
Copilot AI lite review requested due to automatic review settings August 11, 2026 14:07
@javiercn
javiercn requested a review from a team as a code owner August 11, 2026 14:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends the Razor Components metadata generator to compose application-generated component descriptors with framework-owned “built-in” descriptor providers/factories (for Native AOT scenarios), and adds framework-side descriptor providers across Components, Web, Forms, Endpoints, Authorization, QuickGrid, Media, and WebAssembly Authentication.

Changes:

  • Adds framework-owned Microsoft.AspNetCore.Components.Infrastructure.BuiltInComponentDescriptors providers (and generic descriptor factories) across multiple framework assemblies.
  • Updates the generator model and emitter to import referenced provider assemblies/factories and merge them into the generated metadata context output (via UnsafeAccessor bridges).
  • Expands generator test coverage and test infrastructure references to validate provider selection, factory emission, and descriptor correctness.

Reviewed changes

Copilot reviewed 22 out of 23 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/Components/WebAssembly/WebAssembly.Authentication/src/Infrastructure/BuiltInComponentDescriptors.cs Adds WebAssembly Authentication built-in descriptors and RemoteAuthenticatorViewCore factory/injection accessors.
src/Components/Web/src/Metadata/BuiltInComponentDescriptors.cs Adds Web built-in component descriptors and generic factories (e.g., Input*, ValidationMessage, Virtualize) plus accessors.
src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/SampleMetadata.cs Roots representative closed generic component types via [ComponentTypeInfo].
src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj References additional optional framework assemblies to validate provider composition.
src/Components/QuickGrid/Microsoft.AspNetCore.Components.QuickGrid/src/Infrastructure/BuiltInComponentDescriptors.cs Adds QuickGrid built-in descriptors and factories, including Virtualize tuple factory bridging.
src/Components/Media/src/BuiltInComponentDescriptors.cs Adds Media built-in descriptors with required construction patterns and injectable bridges.
src/Components/Forms/src/Infrastructure/BuiltInComponentDescriptors.cs Adds Forms built-in descriptors for DataAnnotationsValidator with accessors.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorTestBase.cs Updates test harness helpers and framework reference loading for new provider assemblies.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorSerializationTests.cs Adjusts serialization tests to filter to referenced-assembly descriptors.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorDiagnosticTests.cs Updates diagnostics assertions to match new generated-source split and filtering.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorComponentTests.cs Adds tests for explicit closed generics and built-in factory emission; updates existing assertions.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorBuiltInDescriptorTests.cs Adds comprehensive provider/factory/descriptor matrix tests for built-in descriptors across assemblies.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests.csproj Adds references required for the expanded built-in descriptor/provider test matrix.
src/Components/Endpoints/src/RazorComponentEndpointHost.cs Switches LayoutAttribute lookup from reflection to resolver-provided metadata (AOT-friendly).
src/Components/Endpoints/src/Infrastructure/BuiltInComponentDescriptors.cs Adds Endpoints built-in descriptors for SSR boundary and endpoint-hosting components plus accessors.
src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs Adds provider inventory, post-init [ComponentTypeInfo] attribute emission, and composition inputs to the model.
src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.Components.cs Adds implicit/explicit built-in factory discovery and adjusts component collection behavior.
src/Components/Endpoints/gen/Models/MetadataContextModel.cs Extends incremental model with built-in provider assemblies and factory models.
src/Components/Endpoints/gen/Emitters/RazorComponentsMetadataGenerator.Emitter.cs Emits built-in provider accessors and factory calls into the generated component descriptor store.
src/Components/Components/src/Infrastructure/BuiltInComponentDescriptors.cs Adds Components built-in descriptors (e.g., Router, SectionOutlet renderer) and owning-component factory.
src/Components/Authorization/src/Infrastructure/BuiltInComponentDescriptors.cs Adds Authorization built-in descriptors, including private-core construction and hidden member accessors.
src/Components/Authorization/src/AuthorizeRouteView.Descriptors.cs Adds internal helpers to construct/access the private AuthorizeRouteView core type for descriptors.
src/Components/Authorization/src/AuthorizeRouteView.cs Makes AuthorizeRouteView partial to host descriptor helper members.
Suppressed comments (1)

src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs:77

  • The generator only collects ClassDeclarationSyntax candidates and casts ctx.Node accordingly. This means a metadata context declared as a record (i.e., record class ... : RazorComponentsMetadataContext) will never be discovered, and none of its metadata (including [ComponentTypeInfo]) will be generated. Since the model/emission already tracks contextType.IsRecord/TypeKeyword, it looks like record contexts are intended to be supported—consider broadening the syntax filter/transform to include RecordDeclarationSyntax (or TypeDeclarationSyntax) and updating the downstream plumbing accordingly.
        var candidates = context.SyntaxProvider
            .CreateSyntaxProvider(
                predicate: static (node, _) => IsCandidateContextDeclaration(node),
                transform: static (ctx, _) => (ClassDeclarationSyntax)ctx.Node)
            .Collect();

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +49 to +54
foreach (var syntaxReference in contextType.DeclaringSyntaxReferences)
{
if (syntaxReference.GetSyntax(cancellationToken) is not ClassDeclarationSyntax declaration)
{
continue;
}
@Youssef1313 Youssef1313 added area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation area-blazor Includes: Blazor, Razor Components labels Sep 2, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Sep 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants