Skip to content

Implement Lazy ResourceDictionary for SourceGen (~8x faster inflation) - #33826

Merged
StephaneDelcroix merged 9 commits into
net11.0from
feature/lazy-resourcedictionary
Mar 4, 2026
Merged

StephaneDelcroix merged 9 commits into
net11.0from
feature/lazy-resourcedictionary

Conversation

@StephaneDelcroix

@StephaneDelcroix StephaneDelcroix commented Feb 1, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Summary

Add lazy resource instantiation to XAML SourceGen. Instead of inflating all Styles, Brushes, and other ResourceDictionary entries upfront, resources are now registered as factory functions and inflated on-demand only when accessed.

Fixes #28985

How It Works

Before: All resources created during page initialization, even if never used.
After: Resources stored as Func<object> factories, inflated only when accessed via StaticResource, DynamicResource, or code.

Performance Results

Benchmark with 63 resources (colors, brushes, styles):

Method Mean Ratio Allocated Alloc Ratio
XamlC (baseline) 336.88 µs 1.00 352.97 KB 1.00
SourceGen LazyRD 43.17 µs 0.14 60.14 KB 0.17
SourceGen (no lazy) 217.30 µs 0.67 258.12 KB 0.73

Key Metrics

  • ⚡ ~8x faster page inflation - defers Style/Brush creation until needed
  • 📉 ~6x less memory at startup - resources created only when accessed
  • 🎯 88% of resources remain unresolved in typical usage

Features

  • AddFactory API on ResourceDictionary for lazy resource registration
  • x:Shared="false" support - each access creates a new instance (fixes crashes with shared StrokeShape)
  • Keys-only resource propagation - prevents premature resolution when adding elements to parent
  • Lazy-friendly ValuesChanged event - uses keys + resolver for on-demand value lookup

Exclusions from Lazy (inflated normally)

Type Reason
Value types No benefit - copied on access
Strings Need TypeConverter processing
Styles with Class attribute Need Add() for class style list
Items with x:Name Need variable for field assignment

Configuration

LazyRD is enabled by default. To opt-out:

<!-- Per-file -->
<MauiXaml Update="file.xaml" LazyRD="false" />

<!-- Global -->
<MauiXamlLazyRD>false</MauiXamlLazyRD>

Testing

  • All 1816 XAML unit tests pass
  • Benchmark included for validation

@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch 6 times, most recently from 7b7fd52 to 53b59db Compare February 2, 2026 12:17
@StephaneDelcroix
StephaneDelcroix marked this pull request as ready for review February 2, 2026 12:18
Copilot AI review requested due to automatic review settings February 2, 2026 12:18
@StephaneDelcroix StephaneDelcroix changed the title Implement Lazy ResourceDictionary with AddFactory API Implement Lazy ResourceDictionary for SourceGen (~8x faster inflation) Feb 2, 2026

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 implements lazy resource creation in ResourceDictionary via factory functions, enabling on-demand instantiation of resources to improve XAML inflation performance and adding support for x:Shared="false" functionality.

Changes:

  • Adds AddFactory API to ResourceDictionary for lazy resource creation with shared/non-shared semantics
  • Implements SourceGen integration to emit AddFactory calls for LazyRD-enabled XAML files
  • Refactors resource change propagation to use keys instead of values to avoid premature lazy resource resolution
  • Adds x:Shared attribute support (SourceGen only) with runtime/XamlC throwing appropriate errors

Reviewed changes

Copilot reviewed 38 out of 38 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/Controls/src/Core/ResourceDictionary.cs AddFactory API, LazyResource wrapper class, resolve-on-access logic, diagnostic support
src/Controls/src/Core/ResourcesChangedEventArgs.cs Key-based resource change propagation to avoid resolving lazy resources
src/Controls/src/Core/Element/Element.cs OnResourcesChangedKeys methods for lazy-aware resource propagation
src/Controls/src/SourceGen/ProjectItem.cs LazyRD property (feature flag with default=true)
src/Controls/src/SourceGen/NodeSGExtensions.cs IsLazyResource detection logic with value type/string exclusions
src/Controls/src/SourceGen/SetPropertyHelpers.cs AddLazyResourceToResourceDictionary emits AddFactory lambdas
src/Controls/src/SourceGen/Visitors/*.cs Visitor changes to skip lazy resources and emit AddFactory calls
src/Controls/src/SourceGen/KnownMarkups.cs StaticResource resolution for lazy resources in lambda contexts
src/Controls/src/Xaml/*.cs x:Shared XML name parsing and runtime error handling
src/Controls/src/Build.Tasks/*.cs XamlC error for x:Shared usage
src/Controls/tests/Core.UnitTests/ResourceDictionaryTests.cs Comprehensive AddFactory API tests including known issues documentation
src/Controls/tests/Xaml.UnitTests/Issues/.xaml XShared and LazyResourceDictionary test files
src/Controls/tests/Xaml.UnitTests/Benchmark*.xaml* Benchmark tests with LazyRD diagnostics
docs/lazy-resourcedictionary-spec.md Comprehensive specification document
PublicAPI.Unshipped.txt New public API surface for AddFactory and ResourcesChangedEventArgs
Microsoft.Maui.Controls.Common.targets MSBuild integration for LazyRD metadata

@StephaneDelcroix StephaneDelcroix added this to the .NET 11.0-preview1 milestone Feb 2, 2026
@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch from 53b59db to 4fed830 Compare February 2, 2026 13:11
@StephaneDelcroix
StephaneDelcroix marked this pull request as draft February 5, 2026 08:52
@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch 3 times, most recently from 559f558 to 13395e8 Compare February 5, 2026 16:09
@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

Dependency Note

During testing of this PR, a pre-existing SourceGen bug was discovered where typed bindings for [ObservableProperty] properties didn't generate setters. This caused crashes in template apps when using SourceGen.

This bug is NOT caused by lazy ResourceDictionary - it reproduces on main branch with SourceGen enabled.

The fix has been extracted to a separate PR: #33914

This PR should be rebased on top of #33914 once it's merged.

@StephaneDelcroix
StephaneDelcroix marked this pull request as ready for review February 6, 2026 08:20
@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 3 pipeline(s).

@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 3 pipeline(s).

@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 3 pipeline(s).

@StephaneDelcroix
StephaneDelcroix changed the base branch from main to net11.0 February 24, 2026 12:21
@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch from ec87011 to 4793ee7 Compare February 24, 2026 20:30
@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch from 4ab6b81 to 8b7edc6 Compare February 27, 2026 15:20
@github-actions

github-actions Bot commented Feb 27, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 33826

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 33826"

@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch from 8b7edc6 to 0a0edfe Compare March 2, 2026 08:58
StephaneDelcroix and others added 8 commits March 3, 2026 17:50
Add lazy resource instantiation to XAML SourceGen for significant
performance improvements. Resources are now created on-demand via
factory functions instead of upfront instantiation.

- AddFactory API on ResourceDictionary for lazy resource registration
- x:Shared="false" support - each access creates a new instance
- Keys-only resource propagation to prevent premature resolution
- Lazy-friendly ValuesChanged event with on-demand value lookup

| Method | Mean | Ratio | Allocated | Alloc Ratio |
|--------|------|-------|-----------|-------------|
| XamlC (baseline) | 336.88 µs | 1.00 | 352.97 KB | 1.00 |
| SourceGen LazyRD | 43.17 µs | 0.14 | 60.14 KB | 0.17 |

- **~8x faster** than XamlC
- **~6x less memory** allocated
- 88% of resources remain unresolved (created only when accessed)

- Value types (no benefit - copied on access)
- Strings (need TypeConverter processing)
- Styles with Class attribute (need Add() for class style list)
- Items with x:Name (need variable for field assignment)

LazyRD is enabled by default. To disable per-file:
  <MauiXaml Update="file.xaml" LazyRD="false" />
Or globally:
  <MauiXamlLazyRD>false</MauiXamlLazyRD>
- Add null check in StaticResourceExtension.CastTo to handle null values
  from lazy resource factories
- Add OnParentResourcesChangedKeys overrides to VisualElement for proper
  key-based resource propagation filtering
- Update test to reflect correct lazy resource resolution behavior

Fixes crash when navigating to ProjectDetailPage in MAUI template with
SourceGen enabled.
When a markup extension (like InvertedBoolConverter) is stored as a lazy
resource in ResourceDictionary, the factory stores the result of
ProvideValue() (e.g., ICommunityToolkitValueConverter), not the original
type (InvertedBoolConverter).

The source generator was incorrectly casting to the original type when
looking up the lazy resource, causing an InvalidCastException at runtime.

This fix checks if the lazy resource type implements IMarkupExtension<T>
and uses the return type T instead of the original declaring type for
the cast expression.
GetDiagnostics() and ResourceDiagnostics are only available in Debug
builds (#if DEBUG in ResourceDictionary.cs). The Benchmark tests that
use these APIs must also be conditionally compiled.
Add SetNamescopesAndRegisterNamesVisitor and SetResourcesVisitor to the
lazy resource lambda body in AddLazyResourceToResourceDictionary(),
matching the established DataTemplate pattern.

Without these visitors, x:Reference inside lazy resources (e.g.
DataTemplates or Styles in ResourceDictionary) could not resolve names
from the outer scope, causing MAUIG1001 errors.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@StephaneDelcroix
StephaneDelcroix force-pushed the feature/lazy-resourcedictionary branch from db87466 to f3a2e1e Compare March 3, 2026 16:51
@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

/azp run maui-pr-devicetests, maui-pr-uitests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

The BOM-prefixed #nullable enable line was sorted to the bottom of the file
instead of remaining at line 1, causing RS0017 analyzer errors.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@StephaneDelcroix

Copy link
Copy Markdown
Contributor Author

/azp run maui-pr-devicetests, maui-pr-uitests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

@StephaneDelcroix
StephaneDelcroix merged commit aa33109 into net11.0 Mar 4, 2026
152 of 209 checks passed
@StephaneDelcroix
StephaneDelcroix deleted the feature/lazy-resourcedictionary branch March 4, 2026 14:54
@github-actions github-actions Bot locked and limited conversation to collaborators Apr 4, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[XAML] Implement x:Shared for StaticResources

4 participants