热更新插件核心约束是不能直接引用主程序类型,必须通过独立契约接口(如IPluginContract.dll)通信,且需用可卸载的AssemblyLoadContext隔离加载,入口通过扫描实现IPlugin的类发现,调试阶段可用dotnet watch监听自动重载。

热更新插件的核心约束:不能直接引用主程序类型
热更新插件本质是运行时动态加载的独立 .dll,一旦插件强依赖主程序的类型(比如继承 BasePlugin 或调用 GameService.Instance.DoWork()),就会导致程序集锁死——下次替换插件时抛出 System.IO.FileLoadException: 无法加载文件或程序集。根本原因在于 .NET 的 Assembly Load Context 默认把所有依赖解析到同一上下文,旧程序集卸载不干净。
可行路径只有一条:插件与宿主通过「契约接口」通信,且该接口必须定义在双方都能访问、但又不随插件更新的独立程序集里(通常叫 IPluginContract.dll)。这个契约程序集需满足:
- 不含任何业务逻辑,仅含 interface 和 DTO 类
- 版本严格固定(如 1.0.0),插件和宿主都引用相同 NuGet 包或本地副本
- 编译目标框架与宿主一致(例如都是 net6.0)
AssemblyLoadContext 隔离加载:避免 AssemblyResolve 陷阱
用 Assembly.LoadFrom() 加载插件是最常见错误——它会把插件及其依赖全部扔进默认上下文,后续无法卸载。正确做法是创建隔离的 AssemblyLoadContext:
public class PluginLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver _resolver;
<pre class="brush:php;toolbar:false;">public PluginLoadContext(string pluginPath) : base(isCollectible: true)
{
_resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
// 契约接口由宿主提供,走默认上下文
if (assemblyName.FullName.StartsWith("IPluginContract"))
{
return Default.LoadFromAssemblyName(assemblyName);
}
return null;
}}
关键点:
- 构造时传入 isCollectible: true,否则无法调用 Unload()
- Load() 中对契约程序集显式委托给 Default,防止重复加载冲突
- 插件内部若反射调用 typeof(MyPlugin).Assembly.GetTypes(),必须确保这些类型没引用宿主私有类型,否则 GetType() 会失败
插件入口发现与生命周期管理:别依赖静态构造函数
插件 DLL 没有 Main 方法,宿主需约定一种可识别的入口类型。推荐方式是扫描实现特定契约接口的非抽象类:
var pluginContext = new PluginLoadContext(pluginPath);
var assembly = pluginContext.LoadFromAssemblyPath(pluginPath);
<p>var pluginType = assembly.GetTypes()
.FirstOrDefault(t => t.IsClass && !t.IsAbstract &&
t.GetInterfaces().Contains(typeof(IPlugin)));</p><p>if (pluginType == null) throw new InvalidOperationException("未找到 IPlugin 实现类");</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2795" title="C#"><img
src="https://img.php.cn/upload/skill/000/000/081/178936933912641.jpg" alt="C#" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="overflowclass">C#</a>
<p class="overflowclass">"避开 C# 常见错误——空陷阱、异步陷阱、LINQ 陷阱及资源泄漏。"</p>
</div>
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>var plugin = (IPlugin)Activator.CreateInstance(pluginType);
plugin.Initialize(); // 由契约定义的初始化方法
</p>
注意:
- 不要用 [Export] 或 MEF,它们隐式依赖 System.ComponentModel.Composition,在 .NET 5+ 中已废弃且与 LoadContext 不兼容
- 插件的 Initialize() 和 Shutdown() 必须是同步方法,避免在 Unload() 后仍有后台线程持有对象引用
- 若插件开启 Timer 或注册事件,必须在 Shutdown() 中显式清理,否则 AssemblyLoadContext.Unload() 会卡住或抛出 InvalidOperationException: Cannot unload a non-collectible AssemblyLoadContext
调试与热替换实操:用 dotnet watch + 文件监听替代手动复制
开发阶段频繁手动替换 DLL 容易出错。更可靠的方式是结合 dotnet watch 监控插件项目输出目录:
在宿主项目中添加以下代码片段(仅用于开发):
if (Debugger.IsAttached)
{
var watcher = new FileSystemWatcher(@"..\..\..\MyPlugin\bin\Debug\net6.0\", "*.dll");
watcher.Changed += (s, e) =>
{
if (e.Name == "MyPlugin.dll")
{
pluginContext?.Unload();
pluginContext = new PluginLoadContext(e.FullPath);
// 重新加载...
}
};
watcher.EnableRaisingEvents = true;
}
同时确保插件项目设置 <copylocallockfileassemblies>true</copylocallockfileassemblies>,避免缺失依赖。正式环境则改用基于时间戳或版本号的校验逻辑触发重载。
最容易被忽略的是:插件 DLL 的 Copy to Output Directory 属性必须设为 Do not copy,否则 Visual Studio 会在编译宿主时自动拷贝旧版插件,掩盖热更新失效问题。









