Supporting Hot Reload in your .NET application

 
 
  • Gérald Barré

Hot Reload is a new feature of .NET 6. The idea is to modify your app source code while the application is running. You don't need to restart it nor to pause it using the debugger. This is just awesome for productivity 😃

Supporting Hot Reload may need some custom logic in your application. For instance, if you use a cache to store reflection data and you add a property to a type, you may need to clear the cache when the application is modified. One example is the json serializer which needs to clear its cache when a type is modified. Another case you may want to support is refreshing UI when the app is modified. One example is Blazor re-rendering the page automatically.

To allow your application to react to Hot Reload, you can register an 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 list of properties of a type. If you add a property using Hot Reload, the application will automatically write the new list of properties 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; }
}

You can now start the application using dotnet watch and start editing the Customer class. You should see the new properties on the console as soon as you save the file:

The application updates its cache and re-render 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?Buy Me A Coffee💖 Sponsor on GitHub