通过应用程序域加载和卸载dll

来源:互联网 发布:卸载kingroot的软件 编辑:程序博客网 时间:2024/05/18 18:54



// 窗体

    public partial class MainWindow : Window
    {
        string dllpath = @"D:\vs\AppDomainTest\TestDll\bin\Debug\TestDll.dll";
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            AppDomain appDomain = AppDomain.CreateDomain("Unload Dll");
            MyMarshalByRefObject m =(MyMarshalByRefObject)appDomain.CreateInstanceFromAndUnwrap(this.GetType().Assembly.Location, "AppDomainTest.MyMarshalByRefObject");
            m.dll_path = dllpath;
            m.Add_LoadResovle();
            m.Load_Dll();
            m.RunCommand();
            m.Remove_LoadResovle();
            AppDomain.Unload(appDomain);

            //以下无法卸载
            //Assembly ab = Assembly.LoadFile(dllpath);
            //Type tp = ab.GetTypes().First();
            //object tdll = ab.CreateInstance(tp.FullName);
            //MethodInfo m = tp.GetMethods().First();
            //m.Invoke(tdll, null);
            //tdll.Run();
        }
    }

    public class MyMarshalByRefObject : MarshalByRefObject
    {
        public string dll_path = string.Empty;
        Assembly assembly = null;


        public void Add_LoadResovle()
        {
            AppDomain.CurrentDomain.AssemblyResolve += LoadAssembly;
        }
        public void Remove_LoadResovle()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= LoadAssembly;
        }
        private Assembly LoadAssembly(object sender, ResolveEventArgs args)
        {
            string dll_name = args.Name.Split(new char[] { ',' }).First();
            if (dll_name.EndsWith("resources")) return null;
            Assembly ab = args.RequestingAssembly;
            DirectoryInfo dir = new FileInfo(ab.Location).Directory;
            foreach(FileInfo f in dir.GetFiles("*.dll",SearchOption.TopDirectoryOnly))
            {
                if (f.Name == dll_name + ".dll")
                {
                    return Assembly.LoadFile(f.FullName);
                }
            }
            MessageBox.Show(args.Name);
            return null;
        }

        public void Load_Dll()
        {
            assembly = Assembly.LoadFile(dll_path);
        }
        public void RunCommand()
        {
            Type tp = assembly.GetTypes().First();
            object tdll = assembly.CreateInstance(tp.FullName);
            MethodInfo m = tp.GetMethods().First();
            m.Invoke(tdll, null);
            //tdll.Run();
        }
    }
}


// 直接加载的dll

    public class TestDll
    {
        public void Run()
        {
            //MessageBox.Show("OK");
            TestDll2.Class1 c = new TestDll2.Class1();
            c.Run();
        }
    }

// 加载dll 的引用

//TestDll2.Class1

    public class Class1
    {
        public void Run()
        {
            System.Windows.Forms.MessageBox.Show("OK");
        }
    }


0 0