dotnet / dotnet/runtime

[API Proposal]: MetadataUpdateHandlerAttribute with BeforeChange method

Open
#129,438 5 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-Diagnostics-coreclr
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

`MetadataUpdateHandlerAttribute` currently supports post-update callbacks such as `ClearCache(Type[]? updatedTypes)` and `UpdateApplication(Type[]? updatedTypes)`. These run after the metadata/code update has already been applied.

I would like to propose adding a pre-update callback, for example:

```csharp
public static void BeforeChange(Type[]? updatedTypes)
```

This method would be invoked before the new code is patched into memory, while the application is still running the old code.

### Motivation

I am building a custom Hot Reload agent and need a way to cleanly unmount the currently running application before the new code is applied, then mount it again using the updated code.

For example, the flow would be:

1. `BeforeChange` runs using the old code and calls `Unmount`
2. Hot Reload applies the new metadata/code update
3. `UpdateApplication` runs using the new code and calls `Mount`

Currently, `ClearCache` and `UpdateApplication` only run after the update, which makes it difficult to execute cleanup logic that must happen against the old implementation before it is replaced.

### API Proposal

```csharp
public static void BeforeChange(Type[]? updatedTypes)
```

### API Usage

```csharp
[assembly: MetadataUpdateHandler(typeof(HotReloadHandler))]

public static class HotReloadHandler
{
public static void BeforeChange(Type[]? updatedTypes)
{
// Runs before the new code is patched into memory.
// This still uses the old code.
AppHost.Current?.Unmount();
}

public static void ClearCache(Type[]? updatedTypes)
{
// Optional: clear caches affected by the update.
}

public static void UpdateApplication(Type[]? updatedTypes)
{
// Runs after the new code is patched into memory.
// This uses the new code.
AppHost.Current?.Mount();
}
}
```

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.