From a4fa2c91663d9be9d03d76c2f8f732da749a9978 Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Fri, 28 Aug 2026 11:55:52 +0200 Subject: [PATCH 1/4] Fix cascading parameter hot reload caching Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Components/src/CascadingParameterState.cs | 11 + .../Components/src/ICascadingValueSupplier.cs | 9 + .../PersistentStateValueProvider.cs | 16 ++ ...stentValueProviderComponentSubscription.cs | 7 + .../Components/src/RenderTree/Renderer.cs | 1 + .../src/Rendering/ComponentState.cs | 32 ++- .../Components/test/CascadingParameterTest.cs | 223 ++++++++++++++++++ 7 files changed, 296 insertions(+), 3 deletions(-) diff --git a/src/Components/Components/src/CascadingParameterState.cs b/src/Components/Components/src/CascadingParameterState.cs index 2193e49b4766..6b9d044fcf29 100644 --- a/src/Components/Components/src/CascadingParameterState.cs +++ b/src/Components/Components/src/CascadingParameterState.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; +using Microsoft.AspNetCore.Components.HotReload; using Microsoft.AspNetCore.Components.Reflection; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; @@ -17,10 +18,20 @@ internal readonly struct CascadingParameterState { private static readonly ConcurrentDictionary _cachedInfos = new(); + static CascadingParameterState() + { + if (HotReloadManager.IsSupported) + { + HotReloadManager.Default.OnDeltaApplied += ClearCache; + } + } + public CascadingParameterInfo ParameterInfo { get; } = parameterInfo; public ICascadingValueSupplier ValueSupplier { get; } = valueSupplier; public object? Key { get; } = key; + internal static void ClearCache() => _cachedInfos.Clear(); + public CascadingParameterState(in CascadingParameterInfo parameterInfo, ICascadingValueSupplier valueSupplier) : this(parameterInfo, valueSupplier, key: null) { } diff --git a/src/Components/Components/src/ICascadingValueSupplier.cs b/src/Components/Components/src/ICascadingValueSupplier.cs index c61362537062..79e4c763e69d 100644 --- a/src/Components/Components/src/ICascadingValueSupplier.cs +++ b/src/Components/Components/src/ICascadingValueSupplier.cs @@ -5,6 +5,12 @@ namespace Microsoft.AspNetCore.Components; +internal enum CascadingParameterSubscriptionMode +{ + Initial, + MetadataRefresh, +} + internal interface ICascadingValueSupplier { bool IsFixed { get; } @@ -15,5 +21,8 @@ internal interface ICascadingValueSupplier void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo); + void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo, CascadingParameterSubscriptionMode mode) + => Subscribe(subscriber, parameterInfo); + void Unsubscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo); } diff --git a/src/Components/Components/src/PersistentState/PersistentStateValueProvider.cs b/src/Components/Components/src/PersistentState/PersistentStateValueProvider.cs index 53158b44e0db..a5e44d5ba012 100644 --- a/src/Components/Components/src/PersistentState/PersistentStateValueProvider.cs +++ b/src/Components/Components/src/PersistentState/PersistentStateValueProvider.cs @@ -39,6 +39,15 @@ public bool CanSupplyValue(in CascadingParameterInfo parameterInfo) } public void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo) + => Subscribe(subscriber, parameterInfo, preserveCurrentValue: false); + + void ICascadingValueSupplier.Subscribe( + ComponentState subscriber, + in CascadingParameterInfo parameterInfo, + CascadingParameterSubscriptionMode mode) + => Subscribe(subscriber, parameterInfo, preserveCurrentValue: mode is CascadingParameterSubscriptionMode.MetadataRefresh); + + private void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo, bool preserveCurrentValue) { var propertyName = parameterInfo.PropertyName; @@ -49,6 +58,13 @@ public void Subscribe(ComponentState subscriber, in CascadingParameterInfo param serviceProvider, logger); + if (preserveCurrentValue) + { + // Registering can queue an initial restore synchronously. A retained component has already + // completed that phase, so initialize the replacement subscription from its current value. + componentSubscription.PreserveCurrentValue(); + } + _subscriptions.Add(new ComponentSubscriptionKey(subscriber, propertyName), componentSubscription); } diff --git a/src/Components/Components/src/PersistentState/PersistentValueProviderComponentSubscription.cs b/src/Components/Components/src/PersistentState/PersistentValueProviderComponentSubscription.cs index 624439c8a592..09f4ac1216c7 100644 --- a/src/Components/Components/src/PersistentState/PersistentValueProviderComponentSubscription.cs +++ b/src/Components/Components/src/PersistentState/PersistentValueProviderComponentSubscription.cs @@ -116,6 +116,13 @@ public PersistentValueProviderComponentSubscription( return _lastValue; } + internal void PreserveCurrentValue() + { + _hasPendingInitialValue = false; + _lastValue = _propertyGetter.GetValue(_subscriber.Component); + _ignoreComponentPropertyValue = false; + } + [UnconditionalSuppressMessage("Trimming", "IL2075:'this' argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to target method. The return value of the source method does not have matching annotations.", Justification = "OpenComponent already has the right set of attributes")] [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "OpenComponent already has the right set of attributes")] [UnconditionalSuppressMessage("Trimming", "IL2072:Target parameter argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to target method. The return value of the source method does not have matching annotations.", Justification = "OpenComponent already has the right set of attributes")] diff --git a/src/Components/Components/src/RenderTree/Renderer.cs b/src/Components/Components/src/RenderTree/Renderer.cs index 015879de2a8d..43130ce39615 100644 --- a/src/Components/Components/src/RenderTree/Renderer.cs +++ b/src/Components/Components/src/RenderTree/Renderer.cs @@ -215,6 +215,7 @@ protected internal ComponentState GetComponentState(IComponent component) private async void RenderRootComponentsOnHotReload() { // Before re-rendering the root component, also clear any well-known caches in the framework + CascadingParameterState.ClearCache(); ComponentFactory.ClearCache(); ComponentProperties.ClearCache(); DefaultComponentActivator.ClearCache(); diff --git a/src/Components/Components/src/Rendering/ComponentState.cs b/src/Components/Components/src/Rendering/ComponentState.cs index f94a52fc5adc..5e96689343f3 100644 --- a/src/Components/Components/src/Rendering/ComponentState.cs +++ b/src/Components/Components/src/Rendering/ComponentState.cs @@ -16,9 +16,10 @@ namespace Microsoft.AspNetCore.Components.Rendering; public class ComponentState : IAsyncDisposable { private readonly Renderer _renderer; - private readonly bool _hasAnyCascadingParameterSubscriptions; + private bool _hasAnyCascadingParameterSubscriptions; private IReadOnlyList _cascadingParameters; private bool _hasCascadingParameters; + private bool _hasCompletedInitialParameterSupply; private bool _hasSingleDeliveryCascadingParameters; private RenderTreeBuilder _nextRenderTree; private ArrayBuilder? _latestDirectParametersSnapshot; // Lazily instantiated @@ -172,6 +173,11 @@ internal void SetDirectParameters(ParameterView parameters) // If we bypass this, the component won't receive the cascading parameters nor // will it update its snapshot of direct parameters. + if (_renderer.IsRenderingOnMetadataUpdate) + { + RefreshCascadingParameters(); + } + if (_hasAnyCascadingParameterSubscriptions) { // We may need to replay these direct parameters later (in NotifyCascadingValueChanged), @@ -194,9 +200,28 @@ internal void SetDirectParameters(ParameterView parameters) } } + _hasCompletedInitialParameterSupply = true; SupplyCombinedParameters(parameters); } + private void RefreshCascadingParameters() + { + if (_hasAnyCascadingParameterSubscriptions) + { + RemoveCascadingParameterSubscriptions(); + } + + _cascadingParameters = CascadingParameterState.FindCascadingParameters(this, out _hasSingleDeliveryCascadingParameters); + _hasCascadingParameters = _cascadingParameters.Count != 0; + + if (_hasCompletedInitialParameterSupply && _hasSingleDeliveryCascadingParameters) + { + StopSupplyingSingleDeliveryCascadingParameters(); + } + + _hasAnyCascadingParameterSubscriptions = AddCascadingParameterSubscriptions(CascadingParameterSubscriptionMode.MetadataRefresh); + } + private void StopSupplyingSingleDeliveryCascadingParameters() { // We're optimizing for the case where there are no single-delivery parameters, or if there were, we already @@ -269,7 +294,8 @@ private void SupplyCombinedParameters(ParameterView directAndCascadingParameters _renderer.AddToPendingTasksWithErrorHandling(setParametersAsyncTask, owningComponentState: this); } - private bool AddCascadingParameterSubscriptions() + private bool AddCascadingParameterSubscriptions( + CascadingParameterSubscriptionMode mode = CascadingParameterSubscriptionMode.Initial) { var hasSubscription = false; var numCascadingParameters = _cascadingParameters!.Count; @@ -279,7 +305,7 @@ private bool AddCascadingParameterSubscriptions() var valueSupplier = _cascadingParameters[i].ValueSupplier; if (!valueSupplier.IsFixed) { - valueSupplier.Subscribe(this, _cascadingParameters[i].ParameterInfo); + valueSupplier.Subscribe(this, _cascadingParameters[i].ParameterInfo, mode); hasSubscription = true; } } diff --git a/src/Components/Components/test/CascadingParameterTest.cs b/src/Components/Components/test/CascadingParameterTest.cs index a083b43091d6..ffb99b3c2114 100644 --- a/src/Components/Components/test/CascadingParameterTest.cs +++ b/src/Components/Components/test/CascadingParameterTest.cs @@ -1,10 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Components.HotReload; +using Microsoft.AspNetCore.Components.Infrastructure; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Test.Helpers; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.Components.Test; @@ -782,6 +785,129 @@ public void OmitsSingleDeliveryCascadingParametersWhenUpdatingDirectParameters() }); } + [Fact] + public async Task HotReloadRefreshesCascadingParametersForRetainedComponents() + { + var supplier = new HotReloadCascadingValueSupplier("Hello", isFixed: true); + var services = new ServiceCollection(); + services.AddSingleton(supplier); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadCascadingParameterConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); + + Assert.Null(component.Value); + Assert.Equal(1, component.NumRenders); + + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Hello", component.Value); + Assert.Equal(2, component.NumRenders); + } + + [Fact] + public async Task HotReloadRefreshesCascadingParameterSubscriptions() + { + var supplier = new HotReloadCascadingValueSupplier("Initial value", isFixed: false); + var services = new ServiceCollection(); + services.AddSingleton(supplier); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadCascadingParameterConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); + + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal(1, supplier.SubscribeCount); + Assert.Equal(0, supplier.UnsubscribeCount); + Assert.Equal(1, supplier.SubscriberCount); + + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal(2, supplier.SubscribeCount); + Assert.Equal(1, supplier.UnsubscribeCount); + Assert.Equal(1, supplier.SubscriberCount); + + supplier.Value = "Updated value"; + await supplier.NotifyChangedAsync(); + + Assert.Equal("Updated value", component.Value); + + supplier.AcceptRefreshedAttributes = false; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal(2, supplier.SubscribeCount); + Assert.Equal(2, supplier.UnsubscribeCount); + Assert.Equal(0, supplier.SubscriberCount); + } + + [Fact] + public async Task HotReloadDoesNotRedeliverSingleDeliveryParametersToRetainedComponents() + { + var supplier = new HotReloadCascadingValueSupplier("Restored value", isFixed: true); + var services = new ServiceCollection(); + services.AddSingleton(supplier); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var retainedComponent = new HotReloadSingleDeliveryParameterConsumer(); + var retainedComponentId = renderer.AssignRootComponentId(retainedComponent); + renderer.RenderRootComponent(retainedComponentId); + + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Initial value", retainedComponent.Value); + Assert.Equal(0, supplier.GetCurrentValueCount); + + var newComponent = new HotReloadSingleDeliveryParameterConsumer(); + var newComponentId = renderer.AssignRootComponentId(newComponent); + renderer.RenderRootComponent(newComponentId); + + Assert.Equal("Restored value", newComponent.Value); + Assert.Equal(1, supplier.GetCurrentValueCount); + } + + [Fact] + public async Task HotReloadPreservesCurrentPersistentStateValue() + { + var persistentComponentState = new PersistentComponentState(new Dictionary(), [], []); + persistentComponentState.InitializeExistingState(new Dictionary(), RestoreContext.InitialValue); + var services = new ServiceCollection(); + services.AddSingleton(serviceProvider => + new PersistentStateValueProvider( + persistentComponentState, + NullLogger.Instance, + serviceProvider)); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadPersistentStateConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); + component.Value = "Current value"; + + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Current value", component.Value); + } + [Fact] public void CanUseTryAddPatternForCascadingValuesInServiceCollection_ValueFactory() { @@ -866,6 +992,103 @@ private class SingleDeliveryValue(string text) public string Text => text; } + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + private class HotReloadCascadingParameterAttribute : CascadingParameterAttributeBase + { + } + + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + private class HotReloadSingleDeliveryCascadingParameterAttribute : CascadingParameterAttributeBase + { + internal override bool SingleDelivery => true; + } + + private sealed class HotReloadCascadingValueSupplier(object value, bool isFixed) : ICascadingValueSupplier + where TAttribute : CascadingParameterAttributeBase + { + private readonly HashSet _subscribers = []; + private TAttribute _initialAttribute; + + public bool AcceptRefreshedAttributes { get; set; } + public int GetCurrentValueCount { get; private set; } + public bool IsFixed => isFixed; + public object Value { get; set; } = value; + public int SubscribeCount { get; private set; } + public int SubscriberCount => _subscribers.Count; + public int UnsubscribeCount { get; private set; } + + public bool CanSupplyValue(in CascadingParameterInfo parameterInfo) + { + if (parameterInfo.Attribute is not TAttribute attribute) + { + return false; + } + + _initialAttribute ??= attribute; + return AcceptRefreshedAttributes && !ReferenceEquals(_initialAttribute, attribute); + } + + public object GetCurrentValue(object key, in CascadingParameterInfo parameterInfo) + { + GetCurrentValueCount++; + return Value; + } + + public void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo) + { + SubscribeCount++; + _subscribers.Add(subscriber); + } + + public void Unsubscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo) + { + UnsubscribeCount++; + _subscribers.Remove(subscriber); + } + + public Task NotifyChangedAsync() + { + var tasks = _subscribers + .Select(subscriber => subscriber.Renderer.Dispatcher.InvokeAsync( + () => subscriber.NotifyCascadingValueChanged(ParameterViewLifetime.Unbound))) + .ToArray(); + + return Task.WhenAll(tasks); + } + } + + private sealed class HotReloadCascadingParameterConsumer : AutoRenderComponent + { + [HotReloadCascadingParameter] + public string Value { get; set; } + + public int NumRenders { get; private set; } + + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + NumRenders++; + builder.AddContent(0, Value); + } + } + + private sealed class HotReloadSingleDeliveryParameterConsumer : AutoRenderComponent + { + [HotReloadSingleDeliveryCascadingParameter] + public string Value { get; set; } = "Initial value"; + + protected override void BuildRenderTree(RenderTreeBuilder builder) + => builder.AddContent(0, Value); + } + + private sealed class HotReloadPersistentStateConsumer : AutoRenderComponent + { + [PersistentState] + public string Value { get; set; } = "Initial value"; + + protected override void BuildRenderTree(RenderTreeBuilder builder) + => builder.AddContent(0, Value); + } + private class SingleDeliveryCascadingParameterAttribute : CascadingParameterAttributeBase { internal override bool SingleDelivery => true; From 0a4dbadf0f8678a6be0ccece7b3f7a1e53863d46 Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Fri, 28 Aug 2026 12:32:28 +0200 Subject: [PATCH 2/4] Add Hot Reload implementation guidance Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/skills/support-hot-reload/SKILL.md | 85 +++++++++++++++++++ .../references/detection.md | 49 +++++++++++ .../references/edit-limits.md | 50 +++++++++++ .../references/mechanisms.md | 78 +++++++++++++++++ .../references/validation.md | 35 ++++++++ src/Components/AGENTS.md | 3 + .../Components/src/ICascadingValueSupplier.cs | 5 ++ .../src/Rendering/ComponentState.cs | 2 + 8 files changed, 307 insertions(+) create mode 100644 .github/skills/support-hot-reload/SKILL.md create mode 100644 .github/skills/support-hot-reload/references/detection.md create mode 100644 .github/skills/support-hot-reload/references/edit-limits.md create mode 100644 .github/skills/support-hot-reload/references/mechanisms.md create mode 100644 .github/skills/support-hot-reload/references/validation.md diff --git a/.github/skills/support-hot-reload/SKILL.md b/.github/skills/support-hot-reload/SKILL.md new file mode 100644 index 000000000000..69e375952a9d --- /dev/null +++ b/.github/skills/support-hot-reload/SKILL.md @@ -0,0 +1,85 @@ +--- +name: support-hot-reload +description: "Make an ASP.NET Core feature work correctly under .NET Hot Reload, and decide whether a feature needs hot-reload work at all. USE FOR: reviewing or writing a feature that caches type/member metadata (reflection results, compiled accessors, attribute lookups, route/endpoint tables, DI activators) and must stay correct when source is edited live; adding a MetadataUpdateHandler / wiring into HotReloadManager to clear caches and refresh on a delta; auditing a PR for a missing hot-reload cache invalidation; understanding what edits Hot Reload supports vs rude edits, and CoreCLR-vs-WebAssembly differences. Triggers on \"does this need hot reload support\", \"add hot reload support\", \"MetadataUpdateHandler\", \"cache not cleared on hot reload\", \"why doesn't my edit apply\". DO NOT USE FOR: writing hot-reload END-TO-END tests as the primary goal, general Blazor authoring, or diagnosing a build failure unrelated to live edits." +--- + +# Support hot reload + +Decide whether a feature needs hot-reload work, and if so, make it correct: when a developer edits source in a running app, any process-wide state the feature derived from the old metadata must be invalidated so the edit takes effect without a restart. Getting this wrong is silent — the app keeps running with stale cached metadata, and the edit only appears after a manual restart, so it is easy to ship a feature that quietly does not hot-reload. + +## Does this feature need hot-reload work? + +A feature needs hot-reload handling when it holds **process-wide state derived from type or member metadata that a source edit can change**. Ask, in order: + +1. Does it keep a `static` (or singleton) cache keyed by `Type`, `MethodInfo`, `PropertyInfo`, or an assembly — holding reflection results, compiled getters/setters/factories, attribute lookups, a route/endpoint table, or model metadata? +2. Is that cache populated once and reused for the life of the process? +3. Would a plausible source edit change what the cache should contain — adding/removing a `[Parameter]`/`[Inject]`/`[Route]`/validation attribute, a member, a route, a render mode, a `[JSInvokable]` method? + +If all three are yes, the feature needs hot-reload handling: the cache must be invalidated on a metadata delta, and any derived runtime structure (a rendered tree, a route/endpoint table, a change token) must be refreshed. If the feature only reads metadata on demand without caching, or its state is per-request, it usually needs nothing. + +The trap is a cache added for performance with no hot-reload wiring. It works in every test that starts fresh and only fails when someone edits the relevant declaration live — see [references/detection.md](references/detection.md) for the full signal list and how to audit a change for a missing invalidation. + +## Adding hot-reload support + +Two mechanisms; pick by whether the runtime hands you the change directly or you piggyback on a framework hub. + +### The metadata update handler (the .NET primitive) +Mark an assembly with a handler type and implement the static methods the runtime calls after applying a delta: + +```csharp +[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(MyFeatureHotReload))] + +internal static class MyFeatureHotReload +{ + // Clear caches first. `updatedTypes` is the changed types, or null = clear everything. + public static void ClearCache(Type[]? updatedTypes) => MyCache.Clear(); + + // Then refresh anything derived from the cache (rebuild a table, fire a change token, re-render). + public static void UpdateApplication(Type[]? updatedTypes) => MyChangeSource.NotifyChanged(); +} +``` + +`ClearCache` runs before `UpdateApplication`; implement whichever you need. Keep the handler type discoverable (a public or internal static type in the same assembly) and the methods exactly `ClearCache(Type[]?)` / `UpdateApplication(Type[]?)`. + +### The ASP.NET Core component hub +Inside the Blazor components stack, the framework already receives the delta and fans it out through `HotReloadManager`: its `UpdateApplication` fires `OnDeltaApplied`. A component-layer cache subscribes and clears itself: + +```csharp +static MyComponentCache() +{ + if (HotReloadManager.IsSupported) + { + HotReloadManager.Default.OnDeltaApplied += ClearCache; + } +} + +public static void ClearCache() => _cache.Clear(); +``` + +This is the pattern the framework's own per-type component caches use (`ComponentProperties`, `DefaultComponentPropertyActivator`, `ComponentFactory`, `DefaultComponentActivator`), and the renderer additionally force-re-renders the root on a delta. Use the hub inside that stack; use the assembly attribute for standalone libraries and non-component features. Details and the ASP.NET Core cache catalog: [references/mechanisms.md](references/mechanisms.md). + +### Refresh retained runtime state + +Clearing the process-wide cache is insufficient when existing runtime objects copied or derived state from it. Identify where the cached result was materialized and make the Hot Reload refresh recompute that state for retained instances. + +If recomputation rebuilds subscriptions, distinguish initial subscription from metadata refresh on the supplier abstraction. The supplier owns replay, destructive reads, and preservation of current values; the generic renderer or coordinator must not branch on concrete supplier types. + +### Completion check +Prove the invalidation works by editing the relevant declaration in a running app under `dotnet watch` and confirming the new behavior appears **without a restart** — asserted on the watch log ("changes applied", no restart), not just on the eventual output, because a rude edit restarts the app and makes a stale cache look fixed. How to validate: [references/validation.md](references/validation.md). + +Permanent regression coverage and live-edit validation serve different purposes: + +- Use focused component or unit tests to deterministically cover cache clearing, retained-state recomputation, and subscription lifecycle. +- Use `dotnet watch` plus a browser to prove the actual metadata delta applies without restart. +- Add E2E coverage only when the existing harness applies the real delta. Do not seed private caches or add test-only endpoints to imitate it. + +## What edits are even possible + +Not every edit can hot-reload; some are "rude edits" that force a restart regardless of your cache handling. Design and test against the real capability set: method/lambda/Razor bodies, adding methods/fields/types/routes/attributes are supported; renaming or deleting a field, changing a field's type, changing a signature in unsupported ways, changing a `const`, and editing startup are rude. Added fields are not re-initialized on existing instances. WebAssembly/Mono supports fewer edits than CoreCLR. The full supported-vs-rude tables, the field-initialization semantics, and the runtime differences: [references/edit-limits.md](references/edit-limits.md). + +## References + +- [references/detection.md](references/detection.md) — the full signal list for "does this need hot-reload work", and how to audit a diff for a missing cache invalidation. +- [references/mechanisms.md](references/mechanisms.md) — the metadata update handler and the `HotReloadManager` hub in depth, the refresh step (change tokens, re-render, endpoint rebuild), and the ASP.NET Core cache catalog with the edit that exercises each. +- [references/edit-limits.md](references/edit-limits.md) — supported vs rude edits with examples, added-field initialization semantics, and CoreCLR vs Blazor WebAssembly capability differences. +- [references/validation.md](references/validation.md) — validating an invalidation works: driving `dotnet watch`, asserting on the watch log, and proving no restart occurred. diff --git a/.github/skills/support-hot-reload/references/detection.md b/.github/skills/support-hot-reload/references/detection.md new file mode 100644 index 000000000000..0377e99a84ba --- /dev/null +++ b/.github/skills/support-hot-reload/references/detection.md @@ -0,0 +1,49 @@ +# Detecting whether a feature needs hot-reload work + +## Table of contents +- [The core question](#the-core-question) +- [Signals that a feature needs handling](#signals-that-a-feature-needs-handling) +- [Signals that it does not](#signals-that-it-does-not) +- [Auditing a change](#auditing-a-change) +- [A cautionary example](#a-cautionary-example) + +## The core question + +A feature needs hot-reload handling when it holds process-wide state derived from type or member metadata that a live source edit can change, and it reuses that state instead of recomputing it. The failure is silent: nothing throws, the app keeps serving, and the edit simply does not take effect until a restart. So the judgment has to be made by inspecting the feature's caching, not by waiting for a test to fail. + +## Signals that a feature needs handling + +Any one of these, combined with reuse across requests, is enough: + +- A `static` or singleton cache keyed by `Type`, `MethodInfo`, `PropertyInfo`, `ParameterInfo`, `ConstructorInfo`, or `Assembly`. +- Cached reflection results: the set of properties/fields/methods of a type, custom-attribute lookups, or `[SomeAttribute]` presence/values. +- Cached compiled accessors built from metadata: expression-tree or delegate getters/setters, an `ObjectFactory`/activator, a parameter-writer, a property-injector. +- A table or map built by scanning types for an attribute: a route table, an endpoint list, a discovered-handler registry, a `[JSInvokable]` method map. +- Model or validation metadata derived from a type's members and their attributes. +- A resolved per-type decision cached as a value: "does this type have attribute X", "what render mode does this component declare", "does this participate in routing". + +The common shape is `ConcurrentDictionary` populated lazily and never cleared. + +## Signals that it does not + +- The feature reads metadata on demand and does not cache it across uses. +- Its state is per-request or per-scope, rebuilt naturally on the next request. +- It caches data that no source edit can change (configuration values, environment, external inputs). +- It is pure runtime state unrelated to type/member shape. + +Startup-only logic is a special case: middleware pipeline, service registration, and route configuration run once at startup and are not re-executed by hot reload. That is not a cache to invalidate — it is an inherent limit (the edit is a rude edit or simply does not re-run), and the right response is to document it, not to wire a handler. The exception is an inline middleware delegate body, whose body edit is a normal method-body delta. + +## Auditing a change + +When reviewing a diff for hot-reload correctness: + +1. Find every new or modified `static`/singleton field that caches something keyed by a metadata identity (the signals above). +2. For each, ask whether a source edit changes what it should hold. If yes, confirm the change also invalidates it — an assembly `[MetadataUpdateHandler]` with a `ClearCache`, or a subscription to the framework hub that clears it. If the invalidation is missing, that is the finding. +3. Confirm the derived runtime structure is also refreshed, not just the cache: a cleared route table must be rebuilt, a cleared metadata cache backing an endpoint list must fire its change token, a component cache clear must be followed by a re-render. Clearing a cache that nothing re-reads until the next natural trigger can still leave stale visible state. +4. Confirm consistency with sibling caches: if analogous caches in the same area subscribe to hot reload and this one does not, that asymmetry is almost always a bug. + +## A worked example + +`CascadingParameterState` in the Blazor components stack caches, per component type, the set of `[CascadingParameterAttributeBase]` properties in a static `ConcurrentDictionary`, populated lazily and reused. It subscribes to the component Hot Reload hub and clears on a delta, matching sibling caches such as `ComponentProperties` and `DefaultComponentPropertyActivator`. + +Clearing is only half of this example. Existing `ComponentState` instances retain the matches and subscriptions derived from the cache, so the renderer also refreshes those retained instances during its forced Hot Reload render. This is the pattern to look for when auditing a metadata cache: invalidate the process-wide source and refresh every longer-lived structure that copied its result. diff --git a/.github/skills/support-hot-reload/references/edit-limits.md b/.github/skills/support-hot-reload/references/edit-limits.md new file mode 100644 index 000000000000..82ba330512ad --- /dev/null +++ b/.github/skills/support-hot-reload/references/edit-limits.md @@ -0,0 +1,50 @@ +# Edit limits: supported vs rude edits + +Cache invalidation only matters for edits the runtime can apply at all. Some edits are "rude edits" that force a restart no matter how correct your handler is. Design and test against the real capability set, and know that a rude edit under `dotnet watch` (with restart-on-rude-edit) restarts the app — which can make a stale cache look fixed, so validation must distinguish the two (see validation.md). + +## Table of contents +- [Supported without restart](#supported-without-restart) +- [Rude edits (restart required)](#rude-edits-restart-required) +- [Added fields are not re-initialized](#added-fields-are-not-re-initialized) +- [CoreCLR vs Blazor WebAssembly](#coreclr-vs-blazor-webassembly) + +## Supported without restart + +Treat these as supported without restart when the target runtime reports the corresponding capabilities (`Baseline AddMethodToExistingType AddStaticFieldToExistingType AddInstanceFieldToExistingType NewTypeDefinition ChangeCustomAttributes UpdateParameters GenericUpdateMethod GenericAddMethodToExistingType GenericAddFieldToExistingType`): + +- Edit an existing method body — `void F() { A(); }` -> `void F() { A(); B(); }`. +- Edit a lambda or local-function body (its signature and captured-variable set must not change). +- Edit Razor markup, an event-handler body, or a `@code` method body — these compile through the Razor source generator to method-body deltas. +- Add a method, a static field, an instance field, or a whole new type. +- Add a new Blazor component / `@page` route (a new type) or a new controller action (a method on an existing type). +- Add or modify custom attributes (not pseudo-custom attributes like `DllImport`/`StructLayout`). +- Add a property (compiles to accessor methods plus, for auto-props, a field). +- Modify generic code (methods and types) on .NET 8+ runtimes. + +## Rude edits (restart required) + +These are rejected as hot-reload deltas; the tooling restarts (or, in an IDE, prompts). Treat each limit against the target runtime and toolchain: + +- Rename a field — rude. +- Delete a field or a type — rude. +- Change a field's type — rude. +- Change a method signature or return type — rude on runtimes without the parameter-update capability; supported on CoreCLR .NET 8+ (and WASM .NET 8+ as a capability, with exceptions below). +- Change a base type or implemented interface — rude. +- Edit around an active statement (e.g. wrap a currently-executing line in try/catch) — rude. +- Change a `const` value — rude; consts are inlined at every use site at compile time, so there is no runtime field to update. +- Edit startup: service registration, middleware, and route configuration run once at startup and do not re-run on hot reload; the source updates but the behavior does not, without a restart. An inline middleware delegate body is the exception (a normal body edit). + +## Added fields are not re-initialized + +Adding an instance or static field is supported, but the runtime does not resize or re-run initializers on objects that already exist. On CoreCLR an added instance field is tracked in a lazy side structure and reads as `default(T)` on pre-existing instances; the field initializer (`= 42`) runs only for instances created after the edit, via the updated constructor. Added static fields likewise start at `default(T)` if the static constructor already ran. Practical consequence: after adding `int _n = 42;`, an already-rendered object shows `0` for `_n`, while a freshly-created one shows `42`. Do not rely on an added field's initializer affecting live instances. + +## CoreCLR vs Blazor WebAssembly + +Blazor Server runs on CoreCLR; Blazor WebAssembly runs on Mono, whose capability set is narrower and set per target framework: + +- WASM before .NET 8: no `AddInstanceFieldToExistingType`, no generic edits, no parameter updates — all rude. WASM .NET 8+ gains instance fields, generic method edits, and parameter updates. +- Even on WASM .NET 8+, adding a new `await` or `yield` (which changes a state machine's shape) is unsupported, and changing a method parameter's name is rude. +- WASM lacks some CoreCLR-only capabilities entirely (e.g. adding an explicit interface implementation). +- Delivery differs: for WASM, the patch is pushed over the browser WebSocket, so an active browser connection is required — a closed/disconnected tab means no delta is delivered. For Blazor Server and other server apps, the patch goes to the server process over a named pipe regardless of the browser; the browser connection is used only for the browser refresh. + +When a feature or edit targets both, validate on both runtimes: an edit that hot-reloads on Server may be a rude edit on WebAssembly. diff --git a/.github/skills/support-hot-reload/references/mechanisms.md b/.github/skills/support-hot-reload/references/mechanisms.md new file mode 100644 index 000000000000..6f42c32ddd91 --- /dev/null +++ b/.github/skills/support-hot-reload/references/mechanisms.md @@ -0,0 +1,78 @@ +# Mechanisms for clearing and refreshing on a delta + +## Table of contents +- [The metadata update handler](#the-metadata-update-handler) +- [The ASP.NET Core component hub](#the-aspnet-core-component-hub) +- [Clear, then refresh](#clear-then-refresh) +- [ASP.NET Core cache catalog](#aspnet-core-cache-catalog) + +## The metadata update handler + +`System.Reflection.Metadata.MetadataUpdateHandlerAttribute` is the .NET primitive. Mark an assembly with a handler type; after the runtime applies a delta it invokes the handler's static methods by convention: + +```csharp +[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(MyFeatureHotReload))] + +internal static class MyFeatureHotReload +{ + public static void ClearCache(Type[]? updatedTypes) => MyCache.Clear(); + public static void UpdateApplication(Type[]? updatedTypes) => MyChangeSource.NotifyChanged(); +} +``` + +Rules that make it actually fire: +- The methods must be named exactly `ClearCache(Type[]?)` and/or `UpdateApplication(Type[]?)`; implement either or both. `ClearCache` is invoked before `UpdateApplication`. +- `updatedTypes` is the set of changed types, or `null` meaning "a change happened but the specific types are unknown — invalidate everything". Handle the `null` case by clearing fully. +- The handler type is referenced only by the attribute, so keep it from being trimmed; a static type in the same assembly as the cache is the normal placement. +- Guard against doing work when hot reload is not active if the clear is expensive; the handler is only called under a delta, but the registration itself should be cheap. + +Use this for standalone libraries and any non-component feature that owns a metadata-derived cache. + +## The ASP.NET Core component hub + +Inside the Blazor components stack the framework already receives the delta and re-broadcasts it, so component-layer caches do not each need an assembly attribute. `HotReloadManager` is itself the `[MetadataUpdateHandler]`; its `UpdateApplication` fires an `OnDeltaApplied` event. A cache subscribes in its static constructor: + +```csharp +static MyComponentCache() +{ + if (HotReloadManager.IsSupported) + { + HotReloadManager.Default.OnDeltaApplied += ClearCache; + } +} + +public static void ClearCache() => _cache.Clear(); +``` + +`HotReloadManager.IsSupported` gates the subscription so nothing is wired when hot reload is unavailable. The renderer subscribes too and, on a delta, clears the core component caches and force-re-renders every root component so the whole tree reflects the edit. Prefer the hub for anything in the components layer; it keeps all component caches on one coherent signal. + +## Clear, then refresh + +Clearing a cache is only half the job. The edit becomes visible only when something re-reads the metadata, so pair the clear with the refresh of whatever was derived from it: + +- A route/endpoint table: rebuild it (Blazor's router clears `RouteTableFactory` and rebuilds on the next refresh; SSR endpoints refresh by cancelling a `CancellationTokenSource` that backs an `IChangeToken` the endpoint data source listens to). +- MVC action/model state: the MVC hot-reload service cancels a token that drives `ActionDescriptorCollection` to rebuild, and clears model-metadata/view/tag-helper caches. +- Rendered UI: after clearing component caches, re-render (the renderer sets a flag that bypasses `ShouldRender` once so every component refreshes). + +If nothing re-reads the cleared cache until an unrelated later trigger, the visible state stays stale even though the cache is technically empty — so make the refresh explicit. + +## ASP.NET Core cache catalog + +The framework's own hot-reload-aware caches, as concrete models. Each lists the metadata it holds and the source edit that must invalidate it. + +Blazor / components (cleared via the hub or the renderer): +- `ComponentProperties._cachedWritersByType` — `[Parameter]`/`[CascadingParameter]` setter writers per component type. Edit: add a `[Parameter]`. +- `CascadingParameterState._cachedInfos` — `[CascadingParameterAttributeBase]` metadata per component type. It clears through `HotReloadManager`; the renderer then refreshes retained `ComponentState` matches and supplier subscriptions. Edit: add or change `[CascadingParameter]` or `[PersistentState]`. +- `DefaultComponentPropertyActivator._cachedPropertyActivators` — compiled `[Inject]` property injectors. Edit: add an `[Inject]` property. +- `ComponentFactory._cachedComponentTypeRenderModes` — the declared `@rendermode` per component. Edit: add/change `@rendermode`. +- `DefaultComponentActivator._cachedComponentTypeInfo` — constructor `ObjectFactory` per component. Edit: change a constructor. +- `RouteTableFactory._cache` (+ `Router`) — the route table keyed by the assembly set. Edit: add/change an `@page` route. +- `EndpointComponentState._streamRenderingAttributeByComponentType` — `[StreamRendering]` per component (also an assembly `[MetadataUpdateHandler]`). Edit: add `[StreamRendering]`. +- `RazorComponentsEndpointHttpContextExtensions` `AcceptsInteractiveRoutingCache` — `[ExcludeFromInteractiveRouting]` per page. Edit: add that attribute. +- `PersistentValueProviderComponentSubscription` — `[PersistentState]` property getters and serializers. Edit: add `[PersistentState]`. +- `EditContextDataAnnotationsExtensions` `_propertyInfoCache` — validated model `PropertyInfo` per `(modelType, field)`. Edit: add a validation attribute to an `EditForm` model. +- `DotNetDispatcher` method caches — `[JSInvokable]` methods per type/assembly. Edit: add a `[JSInvokable]` method. +- Endpoints `HotReloadService` — an `IChangeToken` source that rebuilds the SSR endpoint list. Edit: add an `@page` or change `@rendermode` on an SSR component. + +Shared reflection (assembly `[MetadataUpdateHandler]`): +- `PropertyHelper` `PropertiesCache`/`VisiblePropertiesCache` — public/visible properties per type, the base used by model binding and metadata. Edit: add a public property to a bound model. diff --git a/.github/skills/support-hot-reload/references/validation.md b/.github/skills/support-hot-reload/references/validation.md new file mode 100644 index 000000000000..630f5a0145a8 --- /dev/null +++ b/.github/skills/support-hot-reload/references/validation.md @@ -0,0 +1,35 @@ +# Validating that hot reload works + +An invalidation is only proven when a live edit takes effect **without a restart**. The critical pitfall: if the tooling is configured to restart on a rude edit, a broken hot reload silently falls back to a restart and the edited output still appears — so an assertion that only checks the output passes even when hot reload failed. Validation must assert the mechanism, not just the result. + +## Drive the edit under a watcher + +Run the app under `dotnet watch` (launched so the app uses the runtime under test), reach the state you want to observe, then edit the source file that declares the thing your cache is keyed on (add the `[Parameter]`, the `[CascadingParameter]`, the `@page`, the `[JSInvokable]`). Capture the full watch output at verbose/trace so the hot-reload machinery is logged; the validation artifact is the saved watch log plus the edited source diff and the observed output/DOM before and after the edit. + +```powershell +New-Item -ItemType Directory -Force -Path .\artifacts | Out-Null +dotnet watch --project --verbose run *>&1 | Tee-Object -FilePath .\artifacts\hot-reload-watch.log +``` + +## Assert on the watch log, and on no restart + +Confirm two things from the captured log: + +1. The delta was applied in place — the watcher logs a hot-reload-applied message (an "changes applied" / "Updates applied" style line). Pin the exact strings from a real run against your toolchain; they vary by version. +2. The app did not restart — count a once-per-launch marker (for example the app's "Now listening on:" startup line) before and after the edit and confirm it did not increase. A rude edit instead logs a rude-edit/restart sequence and the launch marker count goes up. + +Then confirm the observable behavior reflects the edit: for server-rendered output, poll the response body and save the before/after snippets; for interactive Blazor, poll the live DOM and save the before/after text or screenshot (the component re-renders in place with no page reload). + +## Distinguish the three outcomes + +- Supported edit, correct invalidation: hot-reload-applied logged, no restart, new behavior visible. +- Supported edit, missing invalidation: hot-reload-applied logged, no restart, but the behavior does not change (the stale cache is still used). This is the assertion that catches a missing `ClearCache` — the delta applied, yet the feature did not react. +- Rude edit: rude-edit/restart logged, launch marker increments; the behavior changes only because the app restarted. Assert the restart, not an in-place apply. + +## Cover both runtimes + +For a feature that runs under both Blazor Server and Blazor WebAssembly, validate on each: the same edit can hot-reload on Server (CoreCLR) yet be a rude edit on WebAssembly (Mono). For WebAssembly, keep a browser connected for the duration, since the delta is delivered over the browser connection. + +## Completion + +The feature's hot-reload support is validated when, for each metadata edit the feature cares about, the validation artifacts show the new behavior with a hot-reload-applied log and no restart, and the diff contains the cache invalidation plus any required refresh signal (`ClearCache`, `OnDeltaApplied`, change-token cancellation, endpoint rebuild, or re-render trigger). If an edit is inherently a rude edit, the validated outcome is a clean restart, documented as a limit rather than a bug. diff --git a/src/Components/AGENTS.md b/src/Components/AGENTS.md index a9d048d4625c..ad04e831d80d 100644 --- a/src/Components/AGENTS.md +++ b/src/Components/AGENTS.md @@ -35,6 +35,9 @@ For implementation work: - Before adding a comment, make local behavior discoverable through precise names, named methods or variables, and smaller single-purpose responsibilities. A named method can improve clarity even when it does not reduce duplication. +- Rely on existing abstractions and extend them with the semantic operation or + context needed by the caller rather than downcasting to a concrete implementation. + Keep implementation-specific lifecycle and state handling behind the abstraction. - Add a concise implementation comment only when a durable nonlocal reason cannot be expressed by structure alone, such as ordering across JavaScript and .NET callbacks, lifecycle ownership transfer, compatibility constraints, or a diff --git a/src/Components/Components/src/ICascadingValueSupplier.cs b/src/Components/Components/src/ICascadingValueSupplier.cs index 79e4c763e69d..714e9c8528e5 100644 --- a/src/Components/Components/src/ICascadingValueSupplier.cs +++ b/src/Components/Components/src/ICascadingValueSupplier.cs @@ -8,9 +8,14 @@ namespace Microsoft.AspNetCore.Components; internal enum CascadingParameterSubscriptionMode { Initial, + + // Rebinds a retained component after its parameter metadata changed. Suppliers must not + // replay values that are valid only during initial parameter supply. MetadataRefresh, } +// Keep supplier-specific behavior behind this abstraction. Callers should extend the contract +// with semantic context instead of depending on concrete ICascadingValueSupplier implementations. internal interface ICascadingValueSupplier { bool IsFixed { get; } diff --git a/src/Components/Components/src/Rendering/ComponentState.cs b/src/Components/Components/src/Rendering/ComponentState.cs index 5e96689343f3..c3f0bd93b6c4 100644 --- a/src/Components/Components/src/Rendering/ComponentState.cs +++ b/src/Components/Components/src/Rendering/ComponentState.cs @@ -206,6 +206,8 @@ internal void SetDirectParameters(ParameterView parameters) private void RefreshCascadingParameters() { + // A metadata update can change both the cascading parameter set and the supplier selected + // for each parameter, so retained component state must rebuild its subscriptions. if (_hasAnyCascadingParameterSubscriptions) { RemoveCascadingParameterSubscriptions(); From 51359cc230d58c3329b179c5d9fa46cd38596d5a Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Fri, 28 Aug 2026 12:36:48 +0200 Subject: [PATCH 3/4] Generalize Hot Reload skill guidance Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/skills/support-hot-reload/SKILL.md | 23 ++++++++------- .../references/detection.md | 10 +++++-- .../references/mechanisms.md | 28 +++++++++++++------ .../references/validation.md | 8 +++--- 4 files changed, 44 insertions(+), 25 deletions(-) diff --git a/.github/skills/support-hot-reload/SKILL.md b/.github/skills/support-hot-reload/SKILL.md index 69e375952a9d..afa526a82147 100644 --- a/.github/skills/support-hot-reload/SKILL.md +++ b/.github/skills/support-hot-reload/SKILL.md @@ -1,6 +1,6 @@ --- name: support-hot-reload -description: "Make an ASP.NET Core feature work correctly under .NET Hot Reload, and decide whether a feature needs hot-reload work at all. USE FOR: reviewing or writing a feature that caches type/member metadata (reflection results, compiled accessors, attribute lookups, route/endpoint tables, DI activators) and must stay correct when source is edited live; adding a MetadataUpdateHandler / wiring into HotReloadManager to clear caches and refresh on a delta; auditing a PR for a missing hot-reload cache invalidation; understanding what edits Hot Reload supports vs rude edits, and CoreCLR-vs-WebAssembly differences. Triggers on \"does this need hot reload support\", \"add hot reload support\", \"MetadataUpdateHandler\", \"cache not cleared on hot reload\", \"why doesn't my edit apply\". DO NOT USE FOR: writing hot-reload END-TO-END tests as the primary goal, general Blazor authoring, or diagnosing a build failure unrelated to live edits." +description: "Make an ASP.NET Core feature work correctly under .NET Hot Reload, and decide whether a feature needs hot-reload work at all. USE FOR: reviewing or writing a feature that caches type/member metadata (reflection results, compiled accessors, attribute lookups, route/endpoint tables, model metadata, DI activators) and must stay correct when source is edited live; adding a MetadataUpdateHandler or integrating with an existing subsystem refresh mechanism; auditing a PR for missing cache invalidation or derived-state refresh; understanding supported versus rude edits and runtime capability differences. Triggers on \"does this need hot reload support\", \"add hot reload support\", \"MetadataUpdateHandler\", \"cache not cleared on hot reload\", \"why doesn't my edit apply\". DO NOT USE FOR: writing end-to-end tests as the primary goal, general application authoring, or diagnosing a build failure unrelated to live edits." --- # Support hot reload @@ -13,7 +13,7 @@ A feature needs hot-reload handling when it holds **process-wide state derived f 1. Does it keep a `static` (or singleton) cache keyed by `Type`, `MethodInfo`, `PropertyInfo`, or an assembly — holding reflection results, compiled getters/setters/factories, attribute lookups, a route/endpoint table, or model metadata? 2. Is that cache populated once and reused for the life of the process? -3. Would a plausible source edit change what the cache should contain — adding/removing a `[Parameter]`/`[Inject]`/`[Route]`/validation attribute, a member, a route, a render mode, a `[JSInvokable]` method? +3. Would a plausible source edit change what the cache should contain — adding or changing a member, controller action, endpoint, route, model property, validation attribute, component parameter, render mode, or invokable method? If all three are yes, the feature needs hot-reload handling: the cache must be invalidated on a metadata delta, and any derived runtime structure (a rendered tree, a route/endpoint table, a change token) must be refreshed. If the feature only reads metadata on demand without caching, or its state is per-request, it usually needs nothing. @@ -21,7 +21,7 @@ The trap is a cache added for performance with no hot-reload wiring. It works in ## Adding hot-reload support -Two mechanisms; pick by whether the runtime hands you the change directly or you piggyback on a framework hub. +Use the runtime metadata-update handler by default. Reuse an existing subsystem refresh mechanism when the owning subsystem already centralizes Hot Reload notifications and derived-state refresh. ### The metadata update handler (the .NET primitive) Mark an assembly with a handler type and implement the static methods the runtime calls after applying a delta: @@ -41,8 +41,11 @@ internal static class MyFeatureHotReload `ClearCache` runs before `UpdateApplication`; implement whichever you need. Keep the handler type discoverable (a public or internal static type in the same assembly) and the methods exactly `ClearCache(Type[]?)` / `UpdateApplication(Type[]?)`. -### The ASP.NET Core component hub -Inside the Blazor components stack, the framework already receives the delta and fans it out through `HotReloadManager`: its `UpdateApplication` fires `OnDeltaApplied`. A component-layer cache subscribes and clears itself: +### Subsystem-specific refresh mechanisms + +Some ASP.NET Core subsystems already receive the runtime delta and coordinate cache clearing with a broader refresh. Reuse that mechanism instead of adding a second independent handler. + +For example, the Components subsystem fans deltas out through `HotReloadManager`: its `UpdateApplication` fires `OnDeltaApplied`, and component-layer caches subscribe and clear themselves: ```csharp static MyComponentCache() @@ -56,7 +59,7 @@ static MyComponentCache() public static void ClearCache() => _cache.Clear(); ``` -This is the pattern the framework's own per-type component caches use (`ComponentProperties`, `DefaultComponentPropertyActivator`, `ComponentFactory`, `DefaultComponentActivator`), and the renderer additionally force-re-renders the root on a delta. Use the hub inside that stack; use the assembly attribute for standalone libraries and non-component features. Details and the ASP.NET Core cache catalog: [references/mechanisms.md](references/mechanisms.md). +This is the pattern the framework's own per-type component caches use (`ComponentProperties`, `DefaultComponentPropertyActivator`, `ComponentFactory`, `DefaultComponentActivator`), and the renderer additionally force-renders roots on a delta. MVC uses its Hot Reload service to clear model/controller/Razor caches and signal action-descriptor changes. Details and the ASP.NET Core cache catalog: [references/mechanisms.md](references/mechanisms.md). ### Refresh retained runtime state @@ -69,17 +72,17 @@ Prove the invalidation works by editing the relevant declaration in a running ap Permanent regression coverage and live-edit validation serve different purposes: -- Use focused component or unit tests to deterministically cover cache clearing, retained-state recomputation, and subscription lifecycle. -- Use `dotnet watch` plus a browser to prove the actual metadata delta applies without restart. +- Use focused unit or integration tests to deterministically cover cache clearing, derived-state recomputation, and lifecycle behavior. +- Use `dotnet watch` plus the appropriate observable boundary—HTTP response, endpoint/action discovery, rendered output, logs, or browser UI—to prove the actual metadata delta applies without restart. - Add E2E coverage only when the existing harness applies the real delta. Do not seed private caches or add test-only endpoints to imitate it. ## What edits are even possible -Not every edit can hot-reload; some are "rude edits" that force a restart regardless of your cache handling. Design and test against the real capability set: method/lambda/Razor bodies, adding methods/fields/types/routes/attributes are supported; renaming or deleting a field, changing a field's type, changing a signature in unsupported ways, changing a `const`, and editing startup are rude. Added fields are not re-initialized on existing instances. WebAssembly/Mono supports fewer edits than CoreCLR. The full supported-vs-rude tables, the field-initialization semantics, and the runtime differences: [references/edit-limits.md](references/edit-limits.md). +Not every edit can hot-reload; some are "rude edits" that force a restart regardless of cache handling. Design and test against the target runtime's real capability set. Added methods, fields, types, and custom attributes are commonly supported; renaming or deleting fields, changing field types, changing constants, and editing startup behavior generally require a restart. Added fields are not initialized on existing instances, and runtime capability sets can differ. See [references/edit-limits.md](references/edit-limits.md) for the detailed tables. ## References - [references/detection.md](references/detection.md) — the full signal list for "does this need hot-reload work", and how to audit a diff for a missing cache invalidation. -- [references/mechanisms.md](references/mechanisms.md) — the metadata update handler and the `HotReloadManager` hub in depth, the refresh step (change tokens, re-render, endpoint rebuild), and the ASP.NET Core cache catalog with the edit that exercises each. +- [references/mechanisms.md](references/mechanisms.md) — the metadata update handler, subsystem refresh mechanisms, the refresh step (change tokens, re-render, endpoint rebuild), and the ASP.NET Core cache catalog with the edit that exercises each. - [references/edit-limits.md](references/edit-limits.md) — supported vs rude edits with examples, added-field initialization semantics, and CoreCLR vs Blazor WebAssembly capability differences. - [references/validation.md](references/validation.md) — validating an invalidation works: driving `dotnet watch`, asserting on the watch log, and proving no restart occurred. diff --git a/.github/skills/support-hot-reload/references/detection.md b/.github/skills/support-hot-reload/references/detection.md index 0377e99a84ba..382ba35db824 100644 --- a/.github/skills/support-hot-reload/references/detection.md +++ b/.github/skills/support-hot-reload/references/detection.md @@ -5,7 +5,7 @@ - [Signals that a feature needs handling](#signals-that-a-feature-needs-handling) - [Signals that it does not](#signals-that-it-does-not) - [Auditing a change](#auditing-a-change) -- [A cautionary example](#a-cautionary-example) +- [Worked examples](#worked-examples) ## The core question @@ -42,8 +42,14 @@ When reviewing a diff for hot-reload correctness: 3. Confirm the derived runtime structure is also refreshed, not just the cache: a cleared route table must be rebuilt, a cleared metadata cache backing an endpoint list must fire its change token, a component cache clear must be followed by a re-render. Clearing a cache that nothing re-reads until the next natural trigger can still leave stale visible state. 4. Confirm consistency with sibling caches: if analogous caches in the same area subscribe to hot reload and this one does not, that asymmetry is almost always a bug. -## A worked example +## Worked examples + +### Components retained state `CascadingParameterState` in the Blazor components stack caches, per component type, the set of `[CascadingParameterAttributeBase]` properties in a static `ConcurrentDictionary`, populated lazily and reused. It subscribes to the component Hot Reload hub and clears on a delta, matching sibling caches such as `ComponentProperties` and `DefaultComponentPropertyActivator`. Clearing is only half of this example. Existing `ComponentState` instances retain the matches and subscriptions derived from the cache, so the renderer also refreshes those retained instances during its forced Hot Reload render. This is the pattern to look for when auditing a metadata cache: invalidate the process-wide source and refresh every longer-lived structure that copied its result. + +### MVC action and model discovery + +MVC's `HotReloadService` coordinates several forms of derived metadata. During the clear phase it invalidates model metadata, controller property activators, and Razor caches. During the update phase it cancels the action-descriptor change token so actions are rediscovered. This demonstrates why cache invalidation and application refresh are separate responsibilities: clearing model metadata alone would not make a newly added action reachable. diff --git a/.github/skills/support-hot-reload/references/mechanisms.md b/.github/skills/support-hot-reload/references/mechanisms.md index 6f42c32ddd91..2f56e8c9ce28 100644 --- a/.github/skills/support-hot-reload/references/mechanisms.md +++ b/.github/skills/support-hot-reload/references/mechanisms.md @@ -2,7 +2,7 @@ ## Table of contents - [The metadata update handler](#the-metadata-update-handler) -- [The ASP.NET Core component hub](#the-aspnet-core-component-hub) +- [Subsystem-specific refresh mechanisms](#subsystem-specific-refresh-mechanisms) - [Clear, then refresh](#clear-then-refresh) - [ASP.NET Core cache catalog](#aspnet-core-cache-catalog) @@ -26,11 +26,13 @@ Rules that make it actually fire: - The handler type is referenced only by the attribute, so keep it from being trimmed; a static type in the same assembly as the cache is the normal placement. - Guard against doing work when hot reload is not active if the clear is expensive; the handler is only called under a delta, but the registration itself should be cheap. -Use this for standalone libraries and any non-component feature that owns a metadata-derived cache. +Use this by default for an assembly that owns a metadata-derived cache unless its subsystem already centralizes Hot Reload notifications and refresh. -## The ASP.NET Core component hub +## Subsystem-specific refresh mechanisms -Inside the Blazor components stack the framework already receives the delta and re-broadcasts it, so component-layer caches do not each need an assembly attribute. `HotReloadManager` is itself the `[MetadataUpdateHandler]`; its `UpdateApplication` fires an `OnDeltaApplied` event. A cache subscribes in its static constructor: +Some subsystems coordinate multiple caches and derived structures through one Hot Reload service. Reuse these mechanisms so cache clearing and application refresh remain ordered. + +In Components, `HotReloadManager` is itself the `[MetadataUpdateHandler]`; its `UpdateApplication` fires an `OnDeltaApplied` event. A cache subscribes in its static constructor: ```csharp static MyComponentCache() @@ -44,7 +46,9 @@ static MyComponentCache() public static void ClearCache() => _cache.Clear(); ``` -`HotReloadManager.IsSupported` gates the subscription so nothing is wired when hot reload is unavailable. The renderer subscribes too and, on a delta, clears the core component caches and force-re-renders every root component so the whole tree reflects the edit. Prefer the hub for anything in the components layer; it keeps all component caches on one coherent signal. +`HotReloadManager.IsSupported` gates the subscription so nothing is wired when Hot Reload is unavailable. The renderer subscribes too and, on a delta, clears core component caches and force-renders every root component. + +MVC uses an assembly metadata-update handler on `HotReloadService`. Its clear phase invalidates model metadata, controller property activators, and Razor state; its update phase cancels the `IActionDescriptorChangeProvider` token so actions are rediscovered. ## Clear, then refresh @@ -52,6 +56,7 @@ Clearing a cache is only half the job. The edit becomes visible only when someth - A route/endpoint table: rebuild it (Blazor's router clears `RouteTableFactory` and rebuilds on the next refresh; SSR endpoints refresh by cancelling a `CancellationTokenSource` that backs an `IChangeToken` the endpoint data source listens to). - MVC action/model state: the MVC hot-reload service cancels a token that drives `ActionDescriptorCollection` to rebuild, and clears model-metadata/view/tag-helper caches. +- A property-backed dictionary or binder: clear its compiled property accessors so the next request sees the new member set. - Rendered UI: after clearing component caches, re-render (the renderer sets a flag that bypasses `ShouldRender` once so every component refreshes). If nothing re-reads the cleared cache until an unrelated later trigger, the visible state stays stale even though the cache is technically empty — so make the refresh explicit. @@ -60,7 +65,15 @@ If nothing re-reads the cleared cache until an unrelated later trigger, the visi The framework's own hot-reload-aware caches, as concrete models. Each lists the metadata it holds and the source edit that must invalidate it. -Blazor / components (cleared via the hub or the renderer): +MVC: +- `HotReloadService` — clears default model metadata, controller property activators, and Razor caches, then signals action-descriptor changes. Edit: add a controller action or change model/Razor metadata. +- `HtmlAttributePropertyHelper` — cached property helpers used for HTML attribute dictionaries. Edit: add or change a model property. + +HTTP and shared infrastructure: +- `RouteValueDictionary._propertyCache` — property accessors used to populate route values from objects. Edit: add or change a public property. +- `PropertyHelper` `PropertiesCache`/`VisiblePropertiesCache` — public/visible properties per type, used by model binding and metadata. Edit: add a public property to a bound model. + +Components: - `ComponentProperties._cachedWritersByType` — `[Parameter]`/`[CascadingParameter]` setter writers per component type. Edit: add a `[Parameter]`. - `CascadingParameterState._cachedInfos` — `[CascadingParameterAttributeBase]` metadata per component type. It clears through `HotReloadManager`; the renderer then refreshes retained `ComponentState` matches and supplier subscriptions. Edit: add or change `[CascadingParameter]` or `[PersistentState]`. - `DefaultComponentPropertyActivator._cachedPropertyActivators` — compiled `[Inject]` property injectors. Edit: add an `[Inject]` property. @@ -73,6 +86,3 @@ Blazor / components (cleared via the hub or the renderer): - `EditContextDataAnnotationsExtensions` `_propertyInfoCache` — validated model `PropertyInfo` per `(modelType, field)`. Edit: add a validation attribute to an `EditForm` model. - `DotNetDispatcher` method caches — `[JSInvokable]` methods per type/assembly. Edit: add a `[JSInvokable]` method. - Endpoints `HotReloadService` — an `IChangeToken` source that rebuilds the SSR endpoint list. Edit: add an `@page` or change `@rendermode` on an SSR component. - -Shared reflection (assembly `[MetadataUpdateHandler]`): -- `PropertyHelper` `PropertiesCache`/`VisiblePropertiesCache` — public/visible properties per type, the base used by model binding and metadata. Edit: add a public property to a bound model. diff --git a/.github/skills/support-hot-reload/references/validation.md b/.github/skills/support-hot-reload/references/validation.md index 630f5a0145a8..39d5f38e86d8 100644 --- a/.github/skills/support-hot-reload/references/validation.md +++ b/.github/skills/support-hot-reload/references/validation.md @@ -4,7 +4,7 @@ An invalidation is only proven when a live edit takes effect **without a restart ## Drive the edit under a watcher -Run the app under `dotnet watch` (launched so the app uses the runtime under test), reach the state you want to observe, then edit the source file that declares the thing your cache is keyed on (add the `[Parameter]`, the `[CascadingParameter]`, the `@page`, the `[JSInvokable]`). Capture the full watch output at verbose/trace so the hot-reload machinery is logged; the validation artifact is the saved watch log plus the edited source diff and the observed output/DOM before and after the edit. +Run the app under `dotnet watch` (launched so the app uses the runtime under test), reach the state you want to observe, then edit the source declaration that the cache derives from—for example, add a controller action, endpoint, route, model property, validation attribute, component parameter, or invokable method. Capture the full watch output at verbose/trace so the Hot Reload machinery is logged; the validation artifact is the saved watch log plus the edited source diff and the observable before and after the edit. ```powershell New-Item -ItemType Directory -Force -Path .\artifacts | Out-Null @@ -18,7 +18,7 @@ Confirm two things from the captured log: 1. The delta was applied in place — the watcher logs a hot-reload-applied message (an "changes applied" / "Updates applied" style line). Pin the exact strings from a real run against your toolchain; they vary by version. 2. The app did not restart — count a once-per-launch marker (for example the app's "Now listening on:" startup line) before and after the edit and confirm it did not increase. A rude edit instead logs a rude-edit/restart sequence and the launch marker count goes up. -Then confirm the observable behavior reflects the edit: for server-rendered output, poll the response body and save the before/after snippets; for interactive Blazor, poll the live DOM and save the before/after text or screenshot (the component re-renders in place with no page reload). +Then confirm the observable behavior reflects the edit at the boundary owned by the feature: inspect HTTP responses, action or endpoint discovery, model/validation behavior, logs, rendered output, or live browser state as applicable. ## Distinguish the three outcomes @@ -26,9 +26,9 @@ Then confirm the observable behavior reflects the edit: for server-rendered outp - Supported edit, missing invalidation: hot-reload-applied logged, no restart, but the behavior does not change (the stale cache is still used). This is the assertion that catches a missing `ClearCache` — the delta applied, yet the feature did not react. - Rude edit: rude-edit/restart logged, launch marker increments; the behavior changes only because the app restarted. Assert the restart, not an in-place apply. -## Cover both runtimes +## Cover the target runtimes -For a feature that runs under both Blazor Server and Blazor WebAssembly, validate on each: the same edit can hot-reload on Server (CoreCLR) yet be a rude edit on WebAssembly (Mono). For WebAssembly, keep a browser connected for the duration, since the delta is delivered over the browser connection. +Validate each runtime and hosting model supported by the feature when their Hot Reload capability or delivery mechanisms differ. For example, an edit can apply on CoreCLR but be rude on Mono; browser-hosted runtimes also require an active browser connection to receive the patch. ## Completion From 02c4d91e0c9712968cd44088e22e46b82213c9f6 Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Fri, 28 Aug 2026 12:58:45 +0200 Subject: [PATCH 4/4] Fix Hot Reload test indentation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Components/test/CascadingParameterTest.cs | 184 +++++++++--------- 1 file changed, 92 insertions(+), 92 deletions(-) diff --git a/src/Components/Components/test/CascadingParameterTest.cs b/src/Components/Components/test/CascadingParameterTest.cs index ffb99b3c2114..034fc5c44b3a 100644 --- a/src/Components/Components/test/CascadingParameterTest.cs +++ b/src/Components/Components/test/CascadingParameterTest.cs @@ -788,124 +788,124 @@ public void OmitsSingleDeliveryCascadingParametersWhenUpdatingDirectParameters() [Fact] public async Task HotReloadRefreshesCascadingParametersForRetainedComponents() { - var supplier = new HotReloadCascadingValueSupplier("Hello", isFixed: true); - var services = new ServiceCollection(); - services.AddSingleton(supplier); - - await using var renderer = new TestRenderer(services.BuildServiceProvider()); - var hotReloadManager = new HotReloadManager(); - renderer.HotReloadManager = hotReloadManager; - var component = new HotReloadCascadingParameterConsumer(); - var componentId = renderer.AssignRootComponentId(component); - renderer.RenderRootComponent(componentId); - - Assert.Null(component.Value); - Assert.Equal(1, component.NumRenders); + var supplier = new HotReloadCascadingValueSupplier("Hello", isFixed: true); + var services = new ServiceCollection(); + services.AddSingleton(supplier); - supplier.AcceptRefreshedAttributes = true; - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadCascadingParameterConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); - Assert.Equal("Hello", component.Value); - Assert.Equal(2, component.NumRenders); + Assert.Null(component.Value); + Assert.Equal(1, component.NumRenders); + + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Hello", component.Value); + Assert.Equal(2, component.NumRenders); } [Fact] public async Task HotReloadRefreshesCascadingParameterSubscriptions() { - var supplier = new HotReloadCascadingValueSupplier("Initial value", isFixed: false); - var services = new ServiceCollection(); - services.AddSingleton(supplier); + var supplier = new HotReloadCascadingValueSupplier("Initial value", isFixed: false); + var services = new ServiceCollection(); + services.AddSingleton(supplier); - await using var renderer = new TestRenderer(services.BuildServiceProvider()); - var hotReloadManager = new HotReloadManager(); - renderer.HotReloadManager = hotReloadManager; - var component = new HotReloadCascadingParameterConsumer(); - var componentId = renderer.AssignRootComponentId(component); - renderer.RenderRootComponent(componentId); + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadCascadingParameterConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); - supplier.AcceptRefreshedAttributes = true; - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); - Assert.Equal(1, supplier.SubscribeCount); - Assert.Equal(0, supplier.UnsubscribeCount); - Assert.Equal(1, supplier.SubscriberCount); + Assert.Equal(1, supplier.SubscribeCount); + Assert.Equal(0, supplier.UnsubscribeCount); + Assert.Equal(1, supplier.SubscriberCount); - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); - Assert.Equal(2, supplier.SubscribeCount); - Assert.Equal(1, supplier.UnsubscribeCount); - Assert.Equal(1, supplier.SubscriberCount); + Assert.Equal(2, supplier.SubscribeCount); + Assert.Equal(1, supplier.UnsubscribeCount); + Assert.Equal(1, supplier.SubscriberCount); - supplier.Value = "Updated value"; - await supplier.NotifyChangedAsync(); + supplier.Value = "Updated value"; + await supplier.NotifyChangedAsync(); - Assert.Equal("Updated value", component.Value); + Assert.Equal("Updated value", component.Value); - supplier.AcceptRefreshedAttributes = false; - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + supplier.AcceptRefreshedAttributes = false; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); - Assert.Equal(2, supplier.SubscribeCount); - Assert.Equal(2, supplier.UnsubscribeCount); - Assert.Equal(0, supplier.SubscriberCount); + Assert.Equal(2, supplier.SubscribeCount); + Assert.Equal(2, supplier.UnsubscribeCount); + Assert.Equal(0, supplier.SubscriberCount); } [Fact] public async Task HotReloadDoesNotRedeliverSingleDeliveryParametersToRetainedComponents() { - var supplier = new HotReloadCascadingValueSupplier("Restored value", isFixed: true); - var services = new ServiceCollection(); - services.AddSingleton(supplier); - - await using var renderer = new TestRenderer(services.BuildServiceProvider()); - var hotReloadManager = new HotReloadManager(); - renderer.HotReloadManager = hotReloadManager; - var retainedComponent = new HotReloadSingleDeliveryParameterConsumer(); - var retainedComponentId = renderer.AssignRootComponentId(retainedComponent); - renderer.RenderRootComponent(retainedComponentId); - - supplier.AcceptRefreshedAttributes = true; - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); - - Assert.Equal("Initial value", retainedComponent.Value); - Assert.Equal(0, supplier.GetCurrentValueCount); - - var newComponent = new HotReloadSingleDeliveryParameterConsumer(); - var newComponentId = renderer.AssignRootComponentId(newComponent); - renderer.RenderRootComponent(newComponentId); - - Assert.Equal("Restored value", newComponent.Value); - Assert.Equal(1, supplier.GetCurrentValueCount); + var supplier = new HotReloadCascadingValueSupplier("Restored value", isFixed: true); + var services = new ServiceCollection(); + services.AddSingleton(supplier); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var retainedComponent = new HotReloadSingleDeliveryParameterConsumer(); + var retainedComponentId = renderer.AssignRootComponentId(retainedComponent); + renderer.RenderRootComponent(retainedComponentId); + + supplier.AcceptRefreshedAttributes = true; + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Initial value", retainedComponent.Value); + Assert.Equal(0, supplier.GetCurrentValueCount); + + var newComponent = new HotReloadSingleDeliveryParameterConsumer(); + var newComponentId = renderer.AssignRootComponentId(newComponent); + renderer.RenderRootComponent(newComponentId); + + Assert.Equal("Restored value", newComponent.Value); + Assert.Equal(1, supplier.GetCurrentValueCount); } [Fact] public async Task HotReloadPreservesCurrentPersistentStateValue() { - var persistentComponentState = new PersistentComponentState(new Dictionary(), [], []); - persistentComponentState.InitializeExistingState(new Dictionary(), RestoreContext.InitialValue); - var services = new ServiceCollection(); - services.AddSingleton(serviceProvider => - new PersistentStateValueProvider( - persistentComponentState, - NullLogger.Instance, - serviceProvider)); - - await using var renderer = new TestRenderer(services.BuildServiceProvider()); - var hotReloadManager = new HotReloadManager(); - renderer.HotReloadManager = hotReloadManager; - var component = new HotReloadPersistentStateConsumer(); - var componentId = renderer.AssignRootComponentId(component); - renderer.RenderRootComponent(componentId); - component.Value = "Current value"; - - hotReloadManager.TriggerOnDeltaApplied(); - await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); - - Assert.Equal("Current value", component.Value); + var persistentComponentState = new PersistentComponentState(new Dictionary(), [], []); + persistentComponentState.InitializeExistingState(new Dictionary(), RestoreContext.InitialValue); + var services = new ServiceCollection(); + services.AddSingleton(serviceProvider => + new PersistentStateValueProvider( + persistentComponentState, + NullLogger.Instance, + serviceProvider)); + + await using var renderer = new TestRenderer(services.BuildServiceProvider()); + var hotReloadManager = new HotReloadManager(); + renderer.HotReloadManager = hotReloadManager; + var component = new HotReloadPersistentStateConsumer(); + var componentId = renderer.AssignRootComponentId(component); + renderer.RenderRootComponent(componentId); + component.Value = "Current value"; + + hotReloadManager.TriggerOnDeltaApplied(); + await renderer.Dispatcher.InvokeAsync(() => Task.CompletedTask); + + Assert.Equal("Current value", component.Value); } [Fact]