AssemblyLoadContext是.NET中实现程序集隔离加载与卸载的核心机制,通过继承并重写Load方法可自定义上下文,利用isCollectible=true支持垃圾回收实现插件热插拔;需定义共享接口、动态加载插件DLL、反射实例化并确保无强引用以完成卸载,适用于构建模块化、可扩展的应用架构。

AssemblyLoadContext 是 .NET 中用于控制程序集(Assembly)加载和卸载的核心机制。与传统的 AppDomain 不同,.NET Core 和 .NET 5+ 移除了对多 AppDomain 的支持,取而代之的是 AssemblyLoadContext,它允许你以隔离的方式加载程序集,并在不需要时进行卸载(配合 GC 实现),非常适合实现插件化架构。
默认情况下,.NET 程序使用一个默认的上下文来加载所有程序集,这些程序集一旦加载就无法单独卸载。而通过自定义 AssemblyLoadContext,你可以:
要实现插件隔离,通常需要继承 AssemblyLoadContext 并重写 Load 方法来处理依赖解析:
using System.Reflection;
using System.Runtime.Loader;
public class PluginLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver _resolver;
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);
}
return null;
}
}
isCollectible: true 表示该上下文可以被垃圾回收,从而实现程序集卸载。
要构建一个可插拔的应用程序,需遵循以下结构:
示例代码(主程序加载插件):
var context = new PluginLoadContext(pluginDllPath);
Assembly assembly = context.LoadFromAssemblyPath(pluginDllPath);
Type pluginType = assembly.GetType("MyPlugin.Plugin");
IPlugin instance = (IPlugin)Activator.CreateInstance(pluginType);
instance.Execute();
// 卸载准备
context.Unload();
// 注意:需确保没有对该上下文中对象的强引用,否则无法回收
以上就是.NET中的AssemblyLoadContext是什么?如何实现插件化架构?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号