C # How to dynamically load and uninstall DLL,
This article introduces how to dynamically load and uninstall DLL in c #. If you need it, refer to it.
In c #, the dll assembly can be loaded dynamically through reflection. However, if you need to update the dll, it is found that the. net class library does not provide the method to uninstall the dll assembly. In. net, the application domain concept is added, and the application domain can be detached. That is to say, if you need to update the Dynamically Loaded dll assembly, you can solve the problem by using the following methods:
Create an application domain, dynamically load the DLL in the application domain, and then uninstall the application domain. When the application domain is uninstalled, related resources are recycled.
To achieve this, you need to let the currentDomain of your program communicate with the newly created newDomain and pass through the boundary of the application domain. I found a solution for a Daniel on the Internet and copied it for myself:
Using System; using System. collections. generic; using System. text; using System. threading; using System. reflection; namespace UnloadDll {class Program {static void Main (string [] args) {string callingDomainName = AppDomain. currentDomain. friendlyName; // Thread. getDomain (). friendlyName; Console. writeLine (callingDomainName); AppDomain ad = AppDomain. createDomain ("DLL Unload test"); ProxyObject obj = (ProxyObject) ad. createInstanceFromAndUnwrap (@ "UnloadDll.exe", "UnloadDll. proxyObject "); obj. loadAssembly (); obj. invoke ("TestDll. class1 "," Test "," It's a test "); AppDomain. unload (ad); obj = null; Console. readLine () ;}} class ProxyObject: externalbyrefobject {Assembly assembly = null; public void LoadAssembly () {assembly = Assembly. loadFile (@ "TestDLL. dll ");} public bool Invoke (string fullClassName, string methodName, params Object [] args) {if (assembly = null) return false; Type tp = assembly. getType (fullClassName); if (tp = null) return false; MethodInfo method = tp. getMethod (methodName); if (method = null) return false; Object obj = Activator. createInstance (tp); method. invoke (obj, args); return true ;}/ * He asked hovertree.com */}
Note:
1. To allow an object to pass through the AppDomain boundary, it must inherit the MarshalByRefObject class; otherwise, it cannot be used by other AppDomains.
2. Each Thread has a default AppDomain, which can be obtained through Thread. GetDomain ().
Recommended:
Http://hovertree.com/h/bjaf/scjyuanma.htm
Http://www.cnblogs.com/roucheng/p/netkuangjia.html