在同個應用程序中不關閉程序實現動態加載同個DLL多次,且DLL內容有更新,程序不會認為是同個DLL
最近做個項目,需要掛載DLL,在DLL更新后不能立刻關閉舊的DLL,因為DLL是一系列的WCF服務。在這種情況下就需要實現動態掛載和卸載DLL,但是一個應用程序在不關閉的情況下只能加載同個DLL一次。
入正題:
private void GetSevList(string dllPath, string sevUri) {
//創建程序域
AppDomainSetup setup = new AppDomainSetup(); ProxyObject po = new ProxyObject(); setup.LoaderOptimization = LoaderOptimization.SingleDomain; setup.ApplicationName = "Test"; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private"); setup.CachePath = setup.ApplicationBase; setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = setup.ApplicationBase;
//使用指定的名稱、證據和應用程序域設置信息創建新的應用程序域。(sevUri 是一個文本值 不重復) AppDomain domain = AppDomain.CreateDomain(sevUri.Split('/')[sevUri.Split('/').Length - 1], null, setup);
string name = Assembly.GetExecutingAssembly().GetName().FullName;
//加載DLL(這個就是需要多次加載的那個DLL) Assembly MyAssembly = po.LoadAssembly(dllPath); po = (ProxyObject)domain.CreateInstanceAndUnwrap(name, typeof(ProxyObject).FullName);
Assembly[] abs = AppDomain.CurrentDomain.GetAssemblies();
}
class ProxyObject : MarshalByRefObject { Assembly assembly = null; public Assembly LoadAssembly(string dllPath) { assembly = Assembly.LoadFile(dllPath); return assembly; } public string FullName { get { return assembly.FullName; } } }
------------付截圖--------------

轉載說明出處
