Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions .github/skills/support-hot-reload/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
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, 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

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

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

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:

```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[]?)`.

### 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()
{
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-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

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 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 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, 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.
55 changes: 55 additions & 0 deletions .github/skills/support-hot-reload/references/detection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# 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)
- [Worked examples](#worked-examples)

## 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<Type, something-derived-from-metadata>` 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.

## Worked examples

### Components retained state

`CascadingParameterState` in the Blazor components stack caches, per component type, the set of `[CascadingParameterAttributeBase]` properties in a static `ConcurrentDictionary<Type, CascadingParameterInfo[]>`, 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.
50 changes: 50 additions & 0 deletions .github/skills/support-hot-reload/references/edit-limits.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading