I'm fairly new to reflection and I was wonder what I would use a (second) AppDomain for? What practical application would one have in a business application?
问题:
回答1:
There are numerous uses. An secondary AppDomain can provide a degree of isolation that is similar to the isolation an OS provides processes.
One practical use that I've used it for is dynamically loading "plug-in" DLLs. I wanted to support scanning a directory for DLLs at startup of the main executable, loading them and checking their types to see if any implemented a specific interface (i.e. the contract of the plug-in). Without creating a secondary AppDomain, you have no way to unload a DLL/assembly that may not have any types that implement the interface sought. Rather than carry around extra assemblies and types, etc. in your process, you can create a secondary AppDomain, load the assembly there and then examine the types. When you're done, you can get rid of the secondary AppDomain and thus your types.
回答2:
99% of the time I would avoid additional AppDomains. They are essentially separate processes. You must marshal data from one domain to the other which adds complexity and performance issues.
People have attempted to use AppDomains to get around the problem that you can't unload assemblies once they have been loaded into an AppDomain. So you create a second AppDomain where you can load your dynamic Assemblies and then unload the complete AppDomain to free the memory associated with the Assemblies.
Unless you need to dynamically load & unload Assemblies they are not really worth worrying about.
回答3:
AppDomains are useful when you have to have multiple instances of a singleton. For example, you have an assembly that implements a communication protocol to some device and this assembly uses singletons. If you want to instantiate multiple instances of this class (to talk to multiple devices) and you want the instances to not interfere with one another, then AppDomains are perfect for this purpose.
It does make programming more difficult, however, as you have to do more work to communicate across AppDomain boundaries.