Hot Reloading in C# with Assembly Context
To achieve hot reloading of code in a C# application while maintaining state, you can use the AssemblyLoadContext feature introduced in .NET Core. This allows you to load assemblies in isolated contexts that can be unloaded and reloaded.
Here's a simple implementation that demonstrates this concept:
Solution Structure
- Main Application - The host application that maintains state
- Plugin Assembly - The code you want to hot reload
Implementation
1. Main Application (Host)
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
public class HotReloadHost
{
private static AssemblyLoadContext _pluginContext;
private static object _pluginInstance;
private static Type _pluginType;
private static MethodInfo _pluginMethod;
private static string _pluginPath = Path.Combine(Directory.GetCurrentDirectory(), "Plugin.dll");
public static void Main()
{
Console.WriteLine("Hot Reload Host Application");
Console.WriteLine("Press R to reload plugin, or any other key to execute");
// Initial load
LoadPlugin();
while (true)
{
var key = Console.ReadKey().Key;
if (key == ConsoleKey.R)
{
ReloadPlugin();
}
else
{
ExecutePlugin();
}
}
}
private static void LoadPlugin()
{
try
{
// Create a new load context
_pluginContext = new AssemblyLoadContext("PluginContext", true);
// Load the assembly
using (var fs = new FileStream(_pluginPath, FileMode.Open, FileAccess.Read))
{
var assembly = _pluginContext.LoadFromStream(fs);
_pluginType = assembly.GetType("Plugin.PluginClass");
_pluginInstance = Activator.CreateInstance(_pluginType);
_pluginMethod = _pluginType.GetMethod("Execute");
}
Console.WriteLine("Plugin loaded successfully");
}
catch (Exception ex)
{
Console.WriteLine($"Error loading plugin: {ex.Message}");
}
}
private static void ReloadPlugin()
{
Console.WriteLine("Reloading plugin...");
// Unload the previous context
if (_pluginContext != null)
{
_pluginContext.Unload();
_pluginContext = null;
}
// Force garbage collection to clean up
GC.Collect();
GC.WaitForPendingFinalizers();
// Load the new version
LoadPlugin();
}
private static void ExecutePlugin()
{
try
{
if (_pluginMethod != null && _pluginInstance != null)
{
var result = _pluginMethod.Invoke(_pluginInstance, null);
Console.WriteLine($"Plugin executed: {result}");
}
else
{
Console.WriteLine("Plugin not loaded");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error executing plugin: {ex.Message}");
}
}
}
2. Plugin Assembly (Plugin.dll)
using System;
namespace Plugin
{
public class PluginClass
{
private static int _counter = 0;
public string Execute()
{
_counter++;
return $"Plugin executed {_counter} times. Current time: {DateTime.Now}";
}
}
}
How to Use This
-
Create a solution with two projects:
- A console application (Host)
- A class library (Plugin)
-
Build the Plugin project first to generate Plugin.dll
-
Run the Host application
-
While the host is running:
- Press any key to execute the plugin
- Press 'R' to reload the plugin (after you've made changes and rebuilt it)
Debugging with Visual Studio
To debug the hot-reloaded code:
- Set breakpoints in your plugin code
- Attach the debugger to the running host process
- When you reload the plugin, the debugger will hit your breakpoints in the new version
Important Notes
-
State Management: The example shows simple state (_counter) that persists between reloads. For more complex state, you'll need to implement proper serialization.
-
Memory Leaks: Be careful with static fields as they can prevent proper unloading of the assembly context.
-
Dependencies: If your plugin has dependencies, you'll need to load them in the same context.
-
Performance: Loading assemblies from streams is more efficient than from files for frequent reloads.
-
Error Handling: The example has basic error handling - you may want to expand it for production use.
This approach gives you the ability to modify and debug your plugin code while maintaining the application state in the host process.