Supporting Hot Reload in your .NET application

 
 
  • Gérald Barré

Hot Reload is a new feature in .NET 6 that lets you modify your application's source code while it is running, without restarting or pausing it with the debugger. It is a great productivity boost!

Supporting Hot Reload may require custom logic in your application. For instance, if you cache reflection data and a property is added to a type, you need to clear that cache when the code changes. The JSON serializer is one such example, as it must clear its cache when a type is modified. Another scenario is refreshing the UI on code changes; Blazor handles this by automatically re-rendering the page.

To allow your application to react to Hot Reload events, you can register a handler using the MetadataUpdateHandler attribute:

C#
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(HotReloadManager))]

internal static class HotReloadManager
{
    public static void ClearCache(Type[]? types) { }
    public static void UpdateApplication(Type[]? types) { }
}

#Demo

Let's build a simple example. The console application displays the properties of a type. When you add a property using Hot Reload, the application automatically prints the updated list to the console.

C#
using System;
using System.Threading.Tasks;
using System.Reflection.Metadata;

[assembly: MetadataUpdateHandler(typeof(HotReloadManager))]

internal static class Program
{
    static void Main()
    {
        Console.WriteLine(PropertyCache.GetProperties<Customer>());
        Console.ReadLine();
    }
}

internal static class HotReloadManager
{
    public static void ClearCache(Type[]? types)
    {
        Console.WriteLine("ClearCache");
        PropertyCache._types.Clear();
    }

    public static void UpdateApplication(Type[]? types)
    {
        // Re-render the list of properties
        Console.WriteLine("UpdateApplication");
        Console.WriteLine(PropertyCache.GetProperties<Customer>());
    }
}

static class PropertyCache
{
    internal static readonly ConcurrentDictionary<Type, string> _types = new();

    public static string GetProperties<T>()
        => _types.GetOrAdd(typeof(T),
            type => string.Join(",", type.GetProperties().Select(p => p.Name)));
}

class Customer
{
    // You can add properties at runtime using Hot Reload
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Start the application with dotnet watch and edit the Customer class. The new properties should appear in the console as soon as you save the file:

The application updates its cache and re-renders when Hot Reload is triggered

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?