Many times, we want to use (develop) USB (hot-swappable) applications, for example, to develop a WinForm application, and this WinForm application allows developers to customize extensions, for example, we may maintain a winservice management system, This winservice system manages a wide variety of services, which are also "plug-in" class libraries, such as:
Public interface IJob { void Run (DateTime time); } public class Collectuserinfo:ijob {public void Run (DateTime time) { //doing some thing ... } }
We provide a ijob interface, all "services" inherit the interface, and then do the related configuration, when the service starts, you can load the assembly according to the configuration, to perform the tasks we expect.
Update assembly (Dll/exe)
Service/plug-ins ( referred to as services later, although they are applied differently, but where they apply the same principles and functions ) are:-). But after the service/plug-in has been running for some time, the business requirements of some "plugins" have changed, or version upgrades and other external causes, we have upgraded the original "plug-in" assembly (may be upgraded from v1.0 to v2.0). When we imagine an ASP. Replace the new DLL with the old one, the error occurs.
The reason for this error is simple, because our program has already called the DLL, then the CLR loaded the DLL into the file stream also lock it, so, when we want to overwrite, modify, delete the time will naturally be unable to manipulate the file. So what are we going to do? Why ASP. NET can directly overwrite ?
AppDomain debut
We know that the AppDomain is a very important feature in the. NET platform, before. NET, each program is "encapsulated" in a different process, resulting in the result of the use of large resources, reusability low disadvantage. While the AppDomain divides multiple "domains" within the same process, A process can run multiple applications, improve the reuse of resources, data communication and so on. See application domains
When the CLR starts, it creates the system domain, the shared domain and the default domain, the system domain and the shared domain are not visible to the user, and the default domain is the current domain. It hosts all kinds of information (stacks) of the current application, so all of our operations are done on this default domain. " Plug-in "development is largely dependent on the AppDomain.
"Hot swap" implementation instructions
When an assembly is loaded, the assembly is added to the specified AppDomain, as the original idea is to implement "hot-swappable", as long as the "plug-in" is needed to load the "plug-in" Assembly (DLL), after the end of use, Uninstalling the Assembly will do what we expect. Loading an assembly is simple,. C # provides a assembly class, convenient and fast.
var _assembly = Assembly.LoadFrom (assemblyfile);
Assembly provides several loading methods as described in the Assembly class.
Then, C # does not provide a way to unload the assembly, and the only way to unload the assembly is to unload the AppDomain where the assembly is located, so that the assemblies under the AppDomain are freed. Knowing this, we can use the AppDomain to achieve our desired results.
AppDomain for "Hot swap"
First, we need to instantiate a new AppDomain as the "plug-in" host. Before instantiating a domain, declare some basic configuration information for that domain
AppDomainSetup Setup = new AppDomainSetup (); Setup. ApplicationName = "Applicationloader"; Setup. ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; Setup. Privatebinpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "private"); Setup. CachePath = Setup. ApplicationBase; Setup. Shadowcopyfiles = "true"; Enable the Image replication assembly Setup. Shadowcopydirectories = Setup. ApplicationBase; AppDomain.CurrentDomain.SetShadowCopyFiles ();
Setup. Shadowcopyfiles = "true"; it is important to enable the image copy assembly, what is the image copy assembly, and the copy assembly is to ensure "hot swap"
Implementation of the main work. When the AppDomain loads the assembly, if there is no shadowcopyfiles, the assembly is loaded directly, and the result is that the assembly is locked, and conversely, if Shadowcopyfiles is enabled, The CLR copies a copy of the assembly that is ready to load to CachePath and then loads the CachePath assembly so that the original assembly is not locked. AppDomain.CurrentDomain.SetShadowCopyFiles (), the role of the current AppDomain is also enabled Shadowcopyfiles, where the current AppDomain is the one we said before the default domain ( Default domain), why do the current domains also have shadowcopyfiles enabled?
The main Appdomian will also add the Assembly to its own assembly reference when calling the child AppDomain to provide the type, method, and property, so the "plug-in" assembly is locked by the master AppDomain. This is also why creating a separate AppDomain assembly does not remove, replace (release) the root cause
With SOS, you can see this very clearly.
0:018>!dumpdomain--------------------------------------System DOMAIN:5B912478LOWFREQUENCYHEAP:5B912784HIGHFR Equencyheap:5b9127d0stubheap:5b91281cstage:openname:none------------------------ --------------Shared domain:5b912140lowfrequencyheap:5b912784highfrequencyheap:5b9127d0stubheap:5b91 281CSTAGE:OPENNAME:NONEASSEMBLY:00109DE0 [C:\Windows\Microsoft.Net\assembly\GAC_32 \mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll]classloader:00110f68 Module Name58631000 C:\Wind Ows\microsoft.net\assembly\gac_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\ mscorlib.dll--------------------------------------Domain 1:000f4598lowfrequencyheap:000f4914highfrequencyhea P:000f4960stubheap:000f49acstage:opensecuritydescriptor:000f5568name:appdomaint EST.EXEASSEMBLY:00109DE0 [C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll]classloader:00110f68securitydescriptor:001097b0 Modul E Name58631000 C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dllAss embly:0011d448 [e:\test\appdomaintest\appdomaintest\bin\debug\appdomaintest.exe]classloader:00117fd0sec URITYDESCRIPTOR:0011D3C0 Module name001c2e9c E:\Test\AppDomainTest\AppDomainTest\bin\Debug\AppDomainTest.exeA ssembly:00131370 [C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e08 9\system.windows.forms.dll]classloader:0011fa00securitydescriptor:001299a0 Module name579c1000 C:\Win Dows\microsoft.net\assembly\gac_msil\system.windows.forms\v4.0_4.0.0.0__b77a5c561934e089\ system.windows.forms.dllassembly:00131400 [C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0 .0__b03f5f7f11d50a3a\system.drawing.dll]classloader: 00131490SECURITYDESCRIPTOR:0012E9C0 Module Name62661000 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.D RAWING\V4.0_4.0.0.0__B03F5F7F11D50A3A\SYSTEM.DRAWING.DLLASSEMBLY:00131D20 [C:\Windows\Microsoft.Net\assembly\GA c_msil\system\v4.0_4.0.0.0__b77a5c561934e089\system.dll]classloader:00133d08securitydescriptor:0012f078 Module N ame5aa81000 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dllAssembly : 00131ed0 [C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\Syste m.configuration.dll]classloader:001415a8securitydescriptor:0012f430 Module name5a981000 C:\Windows\Mi Crosoft.net\assembly\gac_msil\system.configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\ system.configuration.dllassembly:00132080 [C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__ B77a5c561934e089\system.xml.dll]classloader:00141620secuRitydescriptor:0012f5c8 Module name546e1000 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0. 0__b77a5c561934e089\system.xml.dllassembly:00132ce0 [E:\Test\AppDomainTest\AppDomainTest\bin\Debug\CrossDomainC ontroller.dll]classloader:001b3450securitydescriptor:06f94560 Module name001c7428 E:\Test\AppDomainTe st\appdomaintest\bin\debug\crossdomaincontroller.dllassembly:00132350 [C:\Users\kong\AppData\Local\assembly\dl3 \6zyk3xe9.86q\2aq35o7c. vhe\1f704bbb\b7cca5cf_8c4fcc01\showhelloplug.dll]classloader:001b32e8securitydescriptor:070a8620 Module Name001c 7d78 C:\Users\kong\AppData\Local\assembly\dl3\6ZYK3XE9.86Q\2AQ35O7C. Vhe\1f704bbb\b7cca5cf_8c4fcc01\showhelloplug.dll--------------------------------------Domain 2:06fd0238lowfrequ encyheap:06fd05b4highfrequencyheap:06fd0600stubheap:06fd064cstage:opensecuritydescriptor:06 724510name:applicationloaderdOMAINASSEMBLY:00109DE0 [C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorl Ib.dll]classloader:00110f68securitydescriptor:06f93bd0 Module Name58631000 C:\Windows\Microsoft.Net\a Ssembly\gac_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dllassembly:00132e90 [E:\Test\AppDomainTest\App Domaintest\bin\debug\applicationloader\assembly\dl3\c91a2898\f6f7f865_9a4fcc01\crossdomaincontroller.dll] CLASSLOADER:001B3540SECURITYDESCRIPTOR:06F92BE0 Module name00a833c4 E:\Test\AppDomainTest\AppDomainTe st\bin\debug\applicationloader\assembly\dl3\c91a2898\f6f7f865_9a4fcc01\crossdomaincontroller.dllassembly:00133 0d0 [E:\Test\AppDomainTest\AppDomainTest\bin\Debug\ApplicationLoader\assembly\dl3\32519346\b7cca5cf_8c4fcc01\ Showhelloplug.dll]classloader:001b39f0securitydescriptor:06f92f98 Module NAME00A83ADC E:\Test\AppDoma Intest\appdomaintest\bin\debug\applicationloader\assembLy\dl3\32519346\b7cca5cf_8c4fcc01\showhelloplug.dll
In addition to the module in the new AppDomain (Domain2) that references ShowHelloPlug.dll, the default domain (DOMIAN1) also has ShowHelloPlug.dll
Assembly Reference.
Communication between application domains
Each AppDomain has its own stack, memory block, which means that the data between them is not shared. If you want to share data, it involves communication between application domains. C # provides cross-domain communication for the MarshalByRefObject class, so we must provide our own cross-domain accessors.
public class Remoteloader:marshalbyrefobject {private Assembly _assembly; public void loadassembly (string assemblyfile) {try {_assembly = Assembly.Load From (assemblyfile); return _assembly; } catch (Exception ex) {throw ex; }} public T getinstance<t> (string typeName) where T:class {if (_assembly = = NULL ) return null; var type = _assembly. GetType (TypeName); if (type = = NULL) return null; return Activator.CreateInstance (type) as T; The public void Executemothod (string typeName, String methodName) {if (_assembly = = null) return; var type = _assembly. GetType (TypeName); var obj = activator.createinstance (type); Expression<action> lambda = expression.lambda<action> (Expression.call (Expression.constant (obj), type. GetMethod (methodName)), null); Lambda.compile () (); } }
To better manipulate this cross-domain accessor, I then built a class named Assemblydynamicloader, which encapsulates the RemoteLoader class
The operation.
public class Assemblydynamicloader {private AppDomain AppDomain; Private RemoteLoader RemoteLoader; Public Assemblydynamicloader () {appdomainsetup setup = new AppDomainSetup (); Setup. ApplicationName = "Applicationloader"; Setup. ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; Setup. Privatebinpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "private"); Setup. CachePath = Setup. ApplicationBase; Setup. Shadowcopyfiles = "true"; Setup. Shadowcopydirectories = Setup. ApplicationBase; AppDomain.CurrentDomain.SetShadowCopyFiles (); This.appdomain = Appdomain.createdomain ("Applicationloaderdomain", null, Setup); String name = assembly.getexecutingassembly (). GetName (). FullName; This.remoteloader = (remoteloader) this.appDomain.CreateInstanceAndUnwrap (name, typeof (RemoteLoader). FullName); } public void Loadassembly (String assemblyfile) {remoteloader.loadassembly (assemblyfile); Public T getinstance<t> (string typeName) where T:class {if (RemoteLoader = = null) retu RN null; Return remoteloader.getinstance<t> (TypeName); The public void Executemothod (string typeName, String methodName) {Remoteloader.executemothod (type Name, MethodName); The public void Unload () {try {if (AppDomain = = null) return; AppDomain.Unload (This.appdomain); This.appdomain = null; } catch (CannotUnloadAppDomainException ex) {throw ex; } } }
This allows us to cross-domain access each time through the Assemblydynamicloader class.
AppDomain.CurrentDomain.SetShadowCopyFiles (); This.appdomain = Appdomain.createdomain ("Applicationloaderdomain", null, Setup); String name = assembly.getexecutingassembly (). GetName (). FullName; This.remoteloader = (remoteloader) this.appDomain.CreateInstanceAndUnwrap (name, typeof (RemoteLoader). FullName);
Through a AppDomainSetup we constructed earlier, we built an AppDomain that we needed, and built it in this AppDomain.
An instance of the RemoteLoader class where the instance already has cross-domain access, which means that we can get data information inside the subdomain in the primary domain. At present, RemoteLoader only offers a few methods.
Cross-domain operations
Below, we simulate a "plug-in" cross-domain operation. First we construct a form with the following elements.
After you select the assembly path, you load the assembly and then specify the type (obtained by configuration) for the specific action that triggers the assembly. Here we define a common interface, which is the main entry for all "plug-in" operations.
Public interface IPlug { void Run ();
A class that implements the interface is then defined.
[Serializable] public class Showhelloplug:iplug {public void Run () { MessageBox.Show ("Hello world ...");} }
This "plugin" work is simple. Just pop up a dialog box and say "Hello world ..." and then compile it into a DLL.
Back to the interface, select the DLL that you just compiled, and then load it directly.
We have finished half of our work here. OK. Our needs have changed, and we are no longer popping up Hello world. And when the time pops up Hi,i ' m Kinsen, we modify just the subclass and compile it again. Replace the DLL with just the DLL, this time, the DLL is not unlocked (because we have Shadowcopyfiles enabled earlier.) Loading the assembly again, you will find that the result is not "Hi,i ' m Kinsen", but "Hello world." Why is this so? This time, with the help of SOS (the SOS result ahead).
We found that both Domain1 (Default domain) and Domain2 (newly created domain) refer to assembly ShowHelloPlug.DLL, but the DLL addresses for two references are not the same because Shadowcopyfiles is enabled, They load the backup of their respective assemblies, and we view the compiled code for the Showhelloplug based on the assembly address of the Domain2.
0:011>!DUMPMT 00fc40ac 00fc40ac is not a methodtable0:011>!dumpmd 00fc40ac Method Name: Plug.ShowHelloPlug.Run () Class: 046812b4methodtable: 00fc40bcmdtoken: 06000001Module: 00fc3adcisjitted: nocodeaddr: fffffffftransparency:critical
From isjitted to no, you can see that the assembly has not been called, and who is it called? We look at Domain1 again (Default Domain
) in the Showhelloplug.
0:011>!dumpmd 001f8240 Method Name: Plug.ShowHelloPlug.Run () Class: 004446e4methodtable: 001f8250mdtoken: 06000001Module: 001f7d78isjitted: yescodeaddr: 00430de0transparency: Critical
It is known that each AppDomain has its own stack information, each of which does not affect each other, so when we get the data in the primary domain, not a reference to the instance, but rather a piece of space "deep copy" of the instance on its own stack, it is bound to reach the result that we need.
Intra-subdomain invocation
So in order to achieve our desired effect, we have to perform the operations we need within the subdomain (called), so we add an Execute method to the RemoteLoader class
public void Executemothod (string typeName, String methodName) { if (_assembly = = null) return; var type = _assembly. GetType (typeName); var obj = activator.createinstance (type); Expression<action> lambda = expression.lambda<action> (Expression.call (expression.constant (obj), type. GetMethod (methodName)), null); Lambda.compile () (); }
For the moment, I only think of the use of reflection calls, the cost is that the call needs to consume more resources, inefficient. Not yet.
Come up with a better solution, experienced children's shoes welcome communication.
So the external call becomes the following
Loader = new Assemblydynamicloader (); loader. LoadAssembly (txt_dllname.text);//var obj = loader. Getinstance<iplug> ("Plug.showhelloplug");//obj. Run (); loader. Executemothod ("Plug.showhelloplug", "Run");
Now replace the DLL, the result is normal.
End
To do "plug-in" development, in addition to the use of the AppDomain, there are also children's shoes give another solution, that is, when loading the DLL, the DLL in memory to copy one copy, so that the original DLL will not be locked. See "Dynamic Replacement" for plugins.
The above examples I have done experiments, but there may be some deficiencies or conceptual errors, if there are inappropriate, welcome all children shoes criticism pointing.
More
Original address: http://www.cnblogs.com/kongyiyun/archive/2011/08/01/2123459.html
C # Learning Notes-----"plug-in" development based on AppDomain