关于c#动态加载程序集的一些注意事项

Assembly下有LoadFile,LoadFrom等方法能够加载程序集。spa

LoadFile只加载你给定路径的那个dll,LoadFrom会自动加载依赖的dll。code

如:A依赖B,LoadFile(“A”)只会加载A,不会加载B,以后运行A的方法可能会致使报错。继承

LoadFrom(“A”)则会自动加载A和A的依赖,以后调用就不会报错了string

可是若是想要加载进来的程序集还可以卸载掉,就不能用这样的方法了。it

须要用到AppDomain.CreateDomain这样的sandbox型的方法,在以后,再把Create出来的这个AppDomain,Unload掉class

首先,须要继承MarshalByRefObject写一个类 命名空间

在此类中写一个Load方法程序

public class Sandbox : MarshalByRefObject
{
    public void Load(string path)
    {
        Assembly.LoadFrom(path);
    }
}
以后,在住程序中
var ad = AppDomain.CreateDomain("new");
Sandbox sandbox = (Sandbox)ad.CreateInstanceFromAndUnwrap(@"sandbox所在程序集", "命名空间.Sandbox");
sandbox.Load(path);

此时,主程序域中,并无任何你刚刚加载进来的程序集信息,若是须要调用里面的方法,你一样须要经过sandbox去调用。方法

因此sandbox能够增长调用的方法。只有在sandbox中,才能访问当相关的程序集信息。nw

 

最后使用

AppDomain.Unload(ad);
卸载掉
相关文章
相关标签/搜索