c# 动态安装和卸载dll
需求
自动加载指定文件夹下的所有dll文件
第一种方法使用其他框架MAF或MEF
自定义代码
public class PluginLoadContext: AssemblyLoadContext
{
private readonly AssemblyDependencyResolver _resolver;
public PluginLoadContext(string pluginPath)
{
_resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly? Load(AssemblyName assemblyName)
{
var assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
var libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
}
return IntPtr.Zero;
}
}
public void LoadDll(string path)
{
var loadContext = new PluginLoadContext(path);
var assem = loadContext.LoadFromAssemblyName(AssemblyName.GetAssemblyName(path));
if (assem == null)
{
return;
}
var types = assem.GetTypes();
// TODO 获取需要的类
}
可能出现的问题
Q: 在主程序中使用 typeof(IRule).IsAssignableFrom(types[0])
判断是否继承至公共接口,会出现 false
的情况
A:说明 LoadDll
加载dll 时又引入了公共类库,只需要在 dll 解决方案下的依赖项属性中设置 复制本地设为否
(CopyLocal=false
) 即可,或者不要把公共类库复制放到dll所在额文件夹下
IsAssignableFrom() returns false when it should return true
转载请保留原文链接: https://zodream.cn/blog/id/230.html