Skip to content

Defer default MAUI handler activation - #38535

Merged
kubaflo merged 10 commits into
net11.0from
simonrozsival-lazy-maui-handlers
Sep 22, 2026
Merged

kubaflo merged 10 commits into
net11.0from
simonrozsival-lazy-maui-handlers

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

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!

Context

AddControlsHandlers registers the built-in Controls handlers when the MAUI handler collection is first constructed. The default registrations previously used AddHandler<TElement, THandler>(), which immediately evaluates typeof(THandler) and creates a type-based DI descriptor.

On CoreCLR composite-R2R Android startup traces, preparing this registration method caused handler implementation dependencies to be restored and loaded before any of those handlers were needed. In the investigated trace, this included AndroidX RecyclerView, SwipeRefreshLayout, ViewPager2, and CardView while resolving the first application handler.

A factory whose body constructs the handler does not have this behavior: creating and storing the delegate does not materialize the implementation type or load its dependency assemblies. The implementation type must therefore appear only inside the deferred factory body, rather than as a generic handler argument or an eagerly evaluated Type.

Changes

This PR reuses the existing public factory overload:

AddHandler<TElement>(Func<IServiceProvider, IElementHandler> handlerImplementationFactory)

The built-in Controls registrations now use static factories such as:

handlers.AddHandler<CollectionView>(static _ => new CollectionViewHandler());

This still registers typeof(TElement) immediately, so handler lookup and inheritance resolution are unchanged, but the handler implementation is not constructed or materialized until the first request for that element's handler.

No new public API is introduced.

Construction and DI behavior

Most built-in handlers have parameterless constructors. Their factories call those constructors directly, matching the successful path of the previous Activator.CreateInstance(ImplementationType) behavior while avoiding reflection and preserving trimming/AOT visibility through an explicit constructor call.

Using ActivatorUtilities for every handler would add unnecessary reflection-based activation and could select injectable constructors that were not used by the previous registration path. Direct constructors therefore preserve existing default construction semantics more closely.

Handler factories can resolve services registered in either the handler collection or the application/window service provider. Handler-collection services retain precedence. The context-aware provider is also propagated through nested handler-collection factories, so a dependency factory can resolve the same current IMauiContext or Android Context as the top-level handler factory.

Android context-dependent renderers

The legacy Android ListViewRenderer, TableViewRenderer, and FrameRenderer require an Android.Content.Context constructor argument. Previously, type-based registration first failed parameterless activation with MissingMethodException; ElementExtensions.ToHandler then retried with ActivatorUtilities and the current IMauiContext.Context.

Factory registration cannot use that fallback because a factory descriptor has no ImplementationType. This PR adds a narrow internal activation path that invokes handler factories with a provider exposing the current IMauiContext and its window/activity Context, while falling back to the existing handler and application services.

These renderers therefore remain deferred without substituting the global application context, which could change theme and inflater behavior.

Handler type and Hot Reload compatibility

IMauiHandlersFactory.GetHandlerType is used by legacy ListView cell/header reuse logic to determine whether an existing renderer can be reused. Factory descriptors do not expose an implementation type before activation, so the concrete handler type is cached after the factory is invoked.

Hot Reload previously found handler registrations only through ServiceDescriptor.ImplementationType. Factory-activated handlers now also record their concrete type against the exact descriptor. Hot Reload consults that mapping when replacing an active built-in handler, without materializing implementation types during initial registration. Empty pre-activation lookups are not cached, allowing a later activation to establish the mapping.

Before first activation, factory registrations continue to report no handler type. After activation, the cached type preserves the existing ListView reuse and Hot Reload replacement behavior.

Scope

This targets the net11.0 development branch. The change is limited to default handler registration and the internal activation paths required to preserve existing Android, DI, ListView, and Hot Reload behavior.

Validation

  • Existing Core handler hosting tests on net11.0: 26 passed
  • Existing Controls handler hosting tests on net11.0: 9 passed
  • Focused nested factory test confirms the current IMauiContext propagates through handler-collection dependencies
  • Controls.Core Release build for net11.0-android37.0
  • Android-capable local MAUI package set produced at version 11.0.0-preview.7.26464.1

Defer built-in handler implementation activation until first use while preserving Android context-aware renderer construction and handler type reuse.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 14, 2026 16:16
@github-actions

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 -- 38535

Or

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

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

Retarget the lazy default handler registration change to the .NET 11 development branch.

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

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.

Copilot review overview

🟡 Changes recommended

Address the Hot Reload registration mapping and cached-constructor fallback issues.

Get a fresh assessment by requesting another Copilot review.

Review tier: Lite
Findings: 1 Medium severity

Open findings (1)
What changed in this PR

This PR defers built-in MAUI handler activation through factories and provides context-aware activation for Android compatibility renderers.

Changes:

  • Adds context-aware handler activation and type caching.
  • Updates factory infrastructure to pass service providers.
  • Converts built-in handler registrations to deferred factories.
File Summary
src/​Core/​src/​Platform/​ElementExtensions.cs Adds context-aware activation; cached constructor handling can fail after factory registrations are replaced.
src/​Core/​src/​Hosting/​Internal/​MauiHandlersFactory.cs Adds contextual providers and handler-type caching.
src/​Core/​src/​Hosting/​Internal/​MauiFactory.cs Passes selected providers to handler factories.
src/​Controls/​src/​Core/​Hosting/​AppHostBuilderExtensions.cs Converts default handlers to factories; Hot Reload cannot discover these registrations by implementation type.

Copilot AI review requested due to automatic review settings September 14, 2026 16:33
@simonrozsival
simonrozsival changed the base branch from main to net11.0 September 14, 2026 16:33
@github-actions

Copy link
Copy Markdown
Contributor

Skill Validation Results

@simonrozsival — new skill validation results are available based on this last commit: 0dee508.
To request a fresh validation after new comments or commits, comment /evaluate-skills.

Overall Passed Static Passed LLM Skipped Skills 25 Agents 6

✅ Skill Validation Results — 0dee508 · Defer default MAUI handler activation · 2026-09-14T16:35:00Z

✅ Static Checks Passed

Skills: 25 | Eval specs linted: 16

Full lint output
── .github/skills/agentic-labeler/tests/eval.vally.yaml
Vally collects pseudonymous usage telemetry (command name, version, outcome, duration, persistent device identifier (when available), and coarse OS/runtime info) to improve the product. No prompts, datasets, file paths, or arguments are collected.
Opt out any time by setting VALLY_TELEMETRY_OPTOUT=1 or DO_NOT_TRACK=1.
Learn more: https://aka.ms/vally/telemetry
✔ .github/skills/agentic-labeler/tests/eval.vally.yaml is valid
── .github/skills/analyze-sessions/tests/eval.vally.yaml
✔ .github/skills/analyze-sessions/tests/eval.vally.yaml is valid
── .github/skills/ci-fix/tests/eval.ownership.vally.yaml
✔ .github/skills/ci-fix/tests/eval.ownership.vally.yaml is valid
── .github/skills/ci-fix/tests/eval.vally.yaml
✔ .github/skills/ci-fix/tests/eval.vally.yaml is valid
── .github/skills/code-review/tests/eval.inline-findings.vally.yaml
✔ .github/skills/code-review/tests/eval.inline-findings.vally.yaml is valid
── .github/skills/code-review/tests/eval.producer-trace.vally.yaml
✔ .github/skills/code-review/tests/eval.producer-trace.vally.yaml is valid
── .github/skills/code-review/tests/eval.trim-aot.vally.yaml
✔ .github/skills/code-review/tests/eval.trim-aot.vally.yaml is valid
── .github/skills/code-review/tests/eval.vally.yaml
✔ .github/skills/code-review/tests/eval.vally.yaml is valid
── .github/skills/code-review/tests/hermeticity.vally.yaml
✔ .github/skills/code-review/tests/hermeticity.vally.yaml is valid
── .github/skills/code-review/tests/soak.capability.vally.yaml
✔ .github/skills/code-review/tests/soak.capability.vally.yaml is valid
── .github/skills/evaluate-pr-tests/tests/eval.vally.yaml
✔ .github/skills/evaluate-pr-tests/tests/eval.vally.yaml is valid
── .github/skills/pr-review/tests/eval.gh-auth.vally.yaml
✔ .github/skills/pr-review/tests/eval.gh-auth.vally.yaml is valid
── .github/skills/try-fix/tests/eval.restore.vally.yaml
✔ .github/skills/try-fix/tests/eval.restore.vally.yaml is valid
── .github/skills/try-fix/tests/eval.vally.yaml
✔ .github/skills/try-fix/tests/eval.vally.yaml is valid
── .github/skills/verify-tests-fail-without-fix/tests/eval.protocol.vally.yaml
✔ .github/skills/verify-tests-fail-without-fix/tests/eval.protocol.vally.yaml is valid
── .github/skills/verify-tests-fail-without-fix/tests/eval.vally.yaml
✔ .github/skills/verify-tests-fail-without-fix/tests/eval.vally.yaml is valid

⏭️ LLM Evaluation: Skipped

No changed skills with eval specs found.

🔍 Full results and investigation steps

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 14, 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.

Copilot review overview

🟡 Changes recommended

Four unresolved findings remain, including one critical context-propagation issue.

Get a fresh assessment by requesting another Copilot review.

Review tier: Lite
Findings: 1 High severity · 1 Medium severity

Open findings (2)

@kubaflo

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 2 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 14, 2026
@kubaflo

kubaflo commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

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

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15398966 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Sep 21, 2026
@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

Resolve dependency version conflicts with the updated net11.0 values and preserve deferred Windows CollectionView handler activation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 21, 2026 21:13

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.

Copilot review overview

🔵 Needs a closer look

Unresolved moderate findings affect handler type reporting and Hot Reload replacements across handler collections.

Review effort: Lite
Findings: 1 Medium severity

Open (1)

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15404636 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@simonrozsival — test-failure analysis for commit e343ca9.

Scope CI failures Commit e343ca9


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

No results available.


🧪 maui-pr-uitests

No results available.


🧭 Follow-up — actions and refresh

Next action: Comment /azp run maui-pr-devicetests and /azp run maui-pr-uitests to run the missing pipelines.

Maintainers: comment /review tests to refresh this report.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 1 findings

See inline comments for details.

&& serviceDescriptor is not null)
{
return type;
return serviceDescriptor.ImplementationType;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness — GetHandlerType now returns only ImplementationType, so factory-registered handlers keep reporting null even after activation. Concrete failure scenario: Android ListViewRenderer.UpdateHeader / ViewCellRenderer.Update compare GetHandlerType(...) to the current renderer type to decide reuse; with null, they always take the replacement path, repeatedly disconnect/recreate handlers and can regress cell/header reuse behavior and scrolling performance.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@simonrozsival — new AI review results are available based on commit e343ca9.

Gate Passed Confidence Unknown Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: net11.0 · Merge base: b1fccbf6

✅ Verified (new API / feature) — this PR adds new API and a test that references it in the same project, so reverting the fix un-compiles the test: there is no valid "fails without the fix" baseline to establish (a compile-coupled baseline). The gate instead verified the fix by a clean build + pass with the fix, so this is a real PASS rather than a non-committal INCONCLUSIVE.

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 HostBuilderHandlerTests HostBuilderHandlerTests 🛠️ BUILD ERROR ✅ PASS — 52s
🔴 Without fix — 🧪 HostBuilderHandlerTests: 🛠️ BUILD ERROR · 62s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs(402,25): error CS0117: 'MauiHotReloadHelper' does not contain a definition for 'RegisterHandlerReplacement' [/home/vsts/work/1/s/src/Core/tests/UnitTests/Core.UnitTests.csproj]
/home/vsts/work/1/s/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs(428,25): error CS0117: 'MauiHotReloadHelper' does not contain a definition for 'RegisterHandlerReplacement' [/home/vsts/work/1/s/src/Core/tests/UnitTests/Core.UnitTests.csproj]
/home/vsts/work/1/s/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs(459,25): error CS0117: 'MauiHotReloadHelper' does not contain a definition for 'RegisterHandlerType' [/home/vsts/work/1/s/src/Core/tests/UnitTests/Core.UnitTests.csproj]
🟢 With fix — 🧪 HostBuilderHandlerTests: PASS ✅ · 52s

(no coded error found; showing last 1200 chars)

typeof(Microsoft.Maui.UnitTests.Hosting.HostBuilderHandlerTests+MyBaseHandlerStub)) [< 1 ms]
  Passed HostBuilderResolvesClosestApplicableServiceType(type: typeof(Microsoft.Maui.UnitTests.IViewStub), expectedHandlerType: typeof(Microsoft.Maui.UnitTests.ViewHandlerStub)) [1 ms]
  Passed FactoryBasedHandlerRegistrationAppliesPendingHotReloadReplacementOnce [15 ms]
  Passed HostBuilderCannotResolveHandlerTypeForServiceRegisteredWithFactory [1 ms]
  Passed HostBuilderResolvesLastRegisteredHandlerServiceForServiceType [1 ms]
  Passed HostBuilderThrowsWhenNoMatchingHandlerServiceTypeIsRegistered [1 ms]
  Passed HostBuilderResolvesToHandlerRegisteredUnderMostDerivedBaseInterfaceType [1 ms]
[xUnit.net 00:00:01.03]   Finished:    Microsoft.Maui.UnitTests
  Passed HandlerCollectionFactoriesReceiveTheCurrentMauiContext [1 ms]
  Passed FactoryBasedHandlerRegistrationAppliesPendingHotReloadReplacement [2 ms]
  Passed ActivatedHandlerTypeMetadataDoesNotRootServiceDescriptor [19 ms]
  Passed HostBuilderWithDefaultsRegistersMauiHandlersFactory [< 1 ms]
  Passed WindowHandlerFactoriesReceiveTheCurrentMauiContext [9 ms]
Test Run Successful.
Total tests: 32
     Passed: 32
 Total time: 1.8236 Seconds

⚠️ Failure Details

  • 🛠️ HostBuilderHandlerTests without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs(402,25): error CS0117: 'MauiHotReloadHelper' does not contain a definition for 'RegisterHandlerReplacement' [/home/vsts/...
📁 Fix files reverted (12 files)
  • .config/dotnet-tools.json
  • eng/BannedSymbols.txt
  • src/BlazorWebView/src/Maui/MauiBlazorWebViewBuilderExtensions.cs
  • src/Controls/Maps/src/AppHostBuilderExtensions.cs
  • src/Controls/src/Core/Embedding/EmbeddingExtensions.cs
  • src/Controls/src/Core/Handlers/Shell/ShellHandler.Android.cs
  • src/Controls/src/Core/Handlers/Shell/ShellHandler.iOS.cs
  • src/Controls/src/Core/Hosting/AppHostBuilderExtensions.cs
  • src/Core/src/Hosting/Internal/MauiFactory.cs
  • src/Core/src/Hosting/Internal/MauiHandlersFactory.cs
  • src/Core/src/HotReload/HotReloadHelper.cs
  • src/Core/src/Platform/ElementExtensions.cs

📋 Pre-Flight — Context & Validation

Issue: N/A - No linked issue; the PR addresses Android startup dependency-loading cost
PR: #38535 - Defer default MAUI handler activation
Platforms Affected: Android primarily; shared handler registration also affects iOS, MacCatalyst, and Windows
Files Changed: 12 implementation/configuration, 2 test/benchmark

Key Findings

  • The PR changes built-in handler registrations from eager AddHandler<TElement, THandler>() descriptors to implementation factories so handler types and platform dependencies are not materialized until first resolution.
  • To preserve behavior, the PR adds context-aware factory activation, nested service-provider propagation, runtime handler-type metadata for Hot Reload, and context-aware Application, Window, Shell, and ToHandler resolution paths.
  • Prior review feedback led to fixes for nested IMauiContext/IServiceProvider propagation, pre-activation Hot Reload replacements, a weak-key metadata cache, type metadata for the Blazor generic registration, and the banned generic-registration benchmark call.
  • The latest unresolved inline feedback says MauiHandlersFactory.GetHandlerType still returns null after a factory-backed handler activates, which can defeat Android ListView cell/header renderer reuse.
  • Gate passed on Android with the focused HostBuilderHandlerTests target: the PR test is compile-coupled to the new internal APIs, and all 32 focused tests passed with the PR fix. The regression cross-reference result is CLEAN.
  • Detected downstream UI categories are Shell and ViewBaseTests; they belong to the later deep-validation step and are not run during this bounded alternative-generation phase.

Code Review Summary

Verdict: SKIPPED
Confidence: N/A
Errors: 0 | Warnings: 0 | Suggestions: 0

Key code review findings:

  • The separate expert-review pass is intentionally deferred to STEP 5b by the execution contract.
  • Prior inline review context, rather than a new expert assessment, is supplied to the try-fix candidates.

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #38535 Replace default type descriptors with deferred factories and add context-aware activation plus Hot Reload metadata ✅ PASSED (Gate) 14 files Original PR; focused Core tests passed

🔬 Code Review — Deep Analysis

Expert Evaluation — Raw PR Fix

Verdict: NEEDS_CHANGES

The deferred default-handler registration and context-aware activation design is directionally sound, and the submitted tests cover important activation-context, nested-provider, and Hot Reload scenarios. The expert review nevertheless found one concrete Android compatibility regression that should be fixed before approval.

❌ Error — Factory registrations lose reusable handler type identity

src/Core/src/Hosting/Internal/MauiHandlersFactory.cs:56 returns only ServiceDescriptor.ImplementationType. Factory-backed registrations have no implementation type, so GetHandlerType remains null even after a handler has been activated.

Android compatibility ListViewRenderer.UpdateHeader and ViewCellRenderer.Update use GetHandlerType(...) to compare the registered renderer type with an existing renderer before reusing it. A persistent null makes these checks take the teardown/recreation path, risking repeated handler replacement and degraded scrolling behavior.

Required improvement: Preserve the concrete handler type discovered during factory activation and return it from GetHandlerType when the descriptor has no implementation type. Add a regression test proving factory registrations report null before first activation and the concrete type afterward.

Inline findings artifact: CustomAgentLogsTmp/PRState/38535/PRAgent/inline-findings.json


🛠️ Try-Fix — Analysis & Comparison

Fix Candidates

# Source Approach Test Result Files Changed Notes
1 gpt-5.3-codex try-fix Track activated concrete handler types by handler service type inside MauiHandlersFactory, leaving registration/provider flow unchanged ⚠️ BLOCKED None EstablishBrokenBaseline.ps1 rejected pre-existing tracked changes before creating baseline state; no implementation or test was permitted
2 gpt-5.6-sol try-fix Use descriptor-owned symbolic handler type identity resolved through the existing type-activation path, avoiding factories and external activation caches ⚠️ BLOCKED None The same baseline safety check rejected eight pre-existing tracked changes; no implementation or test was permitted
PR PR #38535 Replace default type descriptors with deferred factories and add context-aware activation plus Hot Reload metadata ✅ PASSED (Gate) 14 files Original PR; focused HostBuilderHandlerTests passed

Cross-Pollination

Model Round New Ideas? Details
N/A N/A N/A Skipped by the STEP 5a execution contract

Exhausted: Yes — both permitted model invocations completed; neither could safely establish the broken baseline.
Selected Fix: PR's fix — it is the only implementation with empirical evidence because Gate passed the focused HostBuilderHandlerTests; both alternatives remain unimplemented hypotheses due to the shared environment blocker.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current description claims factory-backed GetHandlerType preserves post-activation ListView renderer reuse, but the submitted PR still returns null; the title also omits the primary platform and component.

Recommended title

[Android] Handlers: Defer default MAUI handler activation

Recommended description

## Context

`AddControlsHandlers` registers the built-in Controls handlers when the MAUI handler collection is first constructed. The default registrations previously used `AddHandler<TElement, THandler>()`, which immediately evaluates `typeof(THandler)` and creates a type-based DI descriptor.

On CoreCLR composite-R2R Android startup traces, preparing this registration method caused handler implementation dependencies to be restored and loaded before any of those handlers were needed. In the investigated trace, this included AndroidX RecyclerView, SwipeRefreshLayout, ViewPager2, and CardView while resolving the first application handler.

A factory whose body constructs the handler does not have this behavior: creating and storing the delegate does not materialize the implementation type or load its dependency assemblies. The implementation type must therefore appear only inside the deferred factory body, rather than as a generic handler argument or an eagerly evaluated `Type`.

## Changes

This PR reuses the existing public factory overload:

```csharp
AddHandler<TElement>(Func<IServiceProvider, IElementHandler> handlerImplementationFactory)

The built-in Controls registrations now use static factories such as:

handlers.AddHandler<CollectionView>(static _ => new CollectionViewHandler());

This still registers typeof(TElement) immediately, so handler lookup and inheritance resolution are unchanged, but the handler implementation is not constructed or materialized until the first request for that element's handler.

No new public API is introduced.

Construction and DI behavior

Most built-in handlers have parameterless constructors. Their factories call those constructors directly, matching the successful path of the previous Activator.CreateInstance(ImplementationType) behavior while avoiding reflection and preserving trimming/AOT visibility through an explicit constructor call.

Using ActivatorUtilities for every handler would add unnecessary reflection-based activation and could select injectable constructors that were not used by the previous registration path. Direct constructors therefore preserve existing default construction semantics more closely.

Handler factories can resolve services registered in either the handler collection or the application/window service provider. Handler-collection services retain precedence. The context-aware provider is also propagated through nested handler-collection factories, so a dependency factory can resolve the same current IMauiContext or Android Context as the top-level handler factory.

Android context-dependent renderers

The legacy Android ListViewRenderer, TableViewRenderer, and FrameRenderer require an Android.Content.Context constructor argument. Previously, type-based registration first failed parameterless activation with MissingMethodException; ElementExtensions.ToHandler then retried with ActivatorUtilities and the current IMauiContext.Context.

Factory registration cannot use that fallback because a factory descriptor has no ImplementationType. This PR adds a narrow internal activation path that invokes handler factories with a provider exposing the current IMauiContext and its window/activity Context, while falling back to the existing handler and application services.

These renderers therefore remain deferred without substituting the global application context, which could change theme and inflater behavior.

Handler type and Hot Reload compatibility

Factory descriptors do not expose an implementation type. Factory-activated handlers now record their concrete type against the exact descriptor, and Hot Reload consults that mapping when replacing an active built-in handler without materializing implementation types during initial registration. Empty pre-activation lookups are not cached, allowing a later activation to establish the Hot Reload mapping.

In the submitted implementation, IMauiHandlersFactory.GetHandlerType still reads only ServiceDescriptor.ImplementationType, so factory registrations report no handler type both before and after activation. Legacy ListView cell/header reuse logic relies on this API to compare an existing renderer's type, so post-activation renderer reuse is not yet preserved by this PR.

Scope

This targets the net11.0 development branch. The shared registration and activation changes affect all platforms, with Android startup dependency loading as the primary motivation and Android context-dependent renderers receiving dedicated handling.

Validation

  • Existing Core handler hosting tests on net11.0: 26 passed
  • Existing Controls handler hosting tests on net11.0: 9 passed
  • Focused nested factory test confirms the current IMauiContext propagates through handler-collection dependencies
  • Controls.Core Release build for net11.0-android37.0
  • Android-capable local MAUI package set produced at version 11.0.0-preview.7.26464.1


</details>

---

<details>
<summary><strong>🏁 Report — Final Recommendation</strong></summary>
<br/>

## ⚠️ Final Recommendation: REQUEST CHANGES

### Winner: `pr-plus-reviewer`

`pr-plus-reviewer` is the only implemented candidate that addresses the expert-confirmed regression while preserving the PR's deferred activation design. It makes the existing descriptor-keyed activated-handler metadata visible to `IMauiHandlersFactory.GetHandlerType`, restoring the post-activation type identity required by Android compatibility ListView renderer reuse.

### Comparative ranking

| Rank | Candidate | Implementation | Regression evidence | Assessment |
|---:|---|---|---|---|
| 1 | `pr-plus-reviewer` | Three-file surgical refinement of the submitted PR | **BLOCKED**, not failed: the one allowed focused run stopped before test execution because `Core.UnitTests/project.assets.json` was absent | Best correctness outcome. It fixes the concrete expert finding and adds the missing pre/post-activation assertion, but requires CI validation after submission. |
| 2 | `pr` | Raw submitted 14-file fix | **PASSED Gate**: tests fail without the PR and all 32 focused tests pass with it | The deferred activation, DI/context propagation, and Hot Reload design is otherwise sound, but the passing tests codify `GetHandlerType == null` after factory activation and therefore miss the Android renderer-reuse regression. |
| 3 | `try-fix-1` | Proposed factory-local activation map keyed by handler service type | **BLOCKED before implementation/testing** | Plausible idea, but no product diff or empirical evidence exists. It also duplicates activated-type state already maintained by the PR. |
| 4 | `try-fix-2` | Proposed symbolic deferred descriptors resolved through the old type-activation path | **BLOCKED before implementation/testing** | Unimplemented and substantially more invasive than reusing the PR's existing descriptor metadata. |

No candidate failed a regression test. The raw PR is the only candidate with a completed passing Gate run; the winner's focused run was blocked by missing restore assets rather than a test failure. That evidence gap lowers confidence but does not outweigh the raw PR's traced correctness defect.

### Expert finding and resolution

The raw PR records a factory-created handler's concrete type in `MauiHotReloadHelper`, but `MauiHandlersFactory.GetHandlerType` reads only `ServiceDescriptor.ImplementationType`. Factory descriptors therefore continue returning `null` after activation. Android `ListViewRenderer.UpdateHeader` and `ViewCellRenderer.Update` use this value to decide whether an existing renderer can be reused, so the raw PR unnecessarily tears down and recreates renderers.

The winning candidate routes `GetHandlerType` through the existing descriptor metadata accessor and updates `HostBuilderHandlerTests` to require `null` before activation and `ViewHandlerStub` afterward. The reviewer-only diff passed `git diff --check` and is persisted at `pr-plus-reviewer/reviewer.patch`.

### Required change

Apply the `pr-plus-reviewer` patch to the submitted PR and run the focused `HostBuilderHandlerTests` in a restored build environment. Approval is not recommended until that candidate compiles and the focused tests pass.


</details>

---

<details>
<summary><strong>📱 UI Tests — Shell,ViewBaseTests</strong></summary>
<br/>

**Detected UI test categories:** `Shell,ViewBaseTests`

<!-- DEEP_UITESTS_BEGIN -->
❌ **Deep UI tests** — 462 passed, 1 failed, 14 skipped across 2 categories on platform-pool agent (replaces in-process counts above).

### 🧪 UI Test Execution Results (deep, platform pool)

| Category | Tests | Snapshot diffs |
|---|---|---|
| `Shell` | 344/358 (1 ❌, 13 skipped) | 1 diff PNG |
| `ViewBaseTests` | 118/119 (1 skipped) ✓ | — |

<details open><summary>🔍 <b>AI analysis of failures — PR-related vs unrelated</b></summary>
<br/>

> 🔍 _AI-generated triage (GitHub Copilot CLI) — a heuristic judgement of whether each deep UI test failure is connected to this PR's changes. Verify before relying on it._

**Likely PR-related:** one or more failures appear connected to this PR's changes.

- **✗ PR-related** — Android Shell navigation-bar visibility (~1 test): `ShellPages_NavBarVisibilityHide` directly exercises Shell on Android, where the PR changes Shell item/section resolution and shared Shell handler registration, which could prevent the expected element from appearing despite the generic timeout symptom.

</details>


<details><summary>❌ <code>Shell</code> — 1 failed test</summary>
<br/>

<details><summary><code>ShellPages_NavBarVisibilityHide</code></summary>
<br/>

System.TimeoutException : Timed out waiting for element...
at UITest.Appium.HelperExtensions.Wait(Func1 query, Func2 satisfactory, String timeoutMessage, Nullable1 timeout, Nullable1 retryFrequency) in //src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2818
at UITest.Appium.HelperExtensions.WaitForAtLeastOne(Func1 query, String timeoutMessage, Nullable1 timeout, Nullable1 retryFrequency) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2845 at UITest.Appium.HelperExtensions.WaitForElement(IApp app, String marked, String timeoutMessage, Nullable1 timeout, Nullable1 retryFrequency, Nullable1 postTimeout) in /
/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 830
at Microsoft.Maui.TestCases.Tests.ShellPagesFeatureTests.ShellPages_NavBarVisibilityHide() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/FeatureMatrix/ShellPagesFeatureTests.cs:line 174
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr*
...


</details>

</details>

📎 [Download `drop-deep-uitests` artifact (TRX + snapshot diffs)](https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=15404636&view=artifacts&pathAsName=false&type=publishedArtifacts)

<!-- DEEP_UITESTS_END -->


</details>

</details>
<!-- SESSION:e343ca9 END -->

---

<details>
<summary><strong>🧭 Next Steps</strong> — reviewer changes required</summary>
<br/>

**The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.**

**Why:** The reviewer refinement fixes the expert-confirmed post-activation handler-type regression by reusing the PR&#39;s existing descriptor metadata, while both try-fix alternatives are unimplemented. Its single targeted validation was blocked by missing restore assets rather than a test failure, so the patch still requires CI confirmation.

Address the actionable findings in this review before merging.

</details>

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Sep 22, 2026
Copilot AI review requested due to automatic review settings September 22, 2026 21:56
@kubaflo
kubaflo merged commit 29e8014 into net11.0 Sep 22, 2026
4 of 15 checks passed
@kubaflo
kubaflo deleted the simonrozsival-lazy-maui-handlers branch September 22, 2026 21:56
@github-actions github-actions Bot added this to the .NET 11.0-rc2 milestone Sep 22, 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.

Copilot review overview

🔵 Needs a closer look

Address the handler type lookup, service-provider contract documentation, and Hot Reload deduplication issues.

Review effort: Lite
Findings: 1 Medium severity

Open (1)

@github-actions github-actions Bot locked and limited conversation to collaborators Oct 23, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants