c# 动态安装和卸载dll

Fork Me On Github
zodream 编程技术 C# 2022年06月

c# 动态安装和卸载dll

需求

自动加载指定文件夹下的所有dll文件

第一种方法使用其他框架MAF或MEF

自定义代码

c#
                                           
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 获取需要的类
}
12345678910111213141516171819202122232425262728293031323334353637383940414243

可能出现的问题

Q: 在主程序中使用 typeof(IRule).IsAssignableFrom(types[0]) 判断是否继承至公共接口,会出现 false 的情况

A:说明 LoadDll 加载dll 时又引入了公共类库,只需要在 dll 解决方案下的依赖项属性中设置 复制本地设为否(CopyLocal=false) 即可,或者不要把公共类库复制放到dll所在额文件夹下

IsAssignableFrom() returns false when it should return true

点击查看全文
0 692 0