tags:

views:

1451

answers:

5

I would like to know how to unload an assembly that is loaded into the main appdomain.

I have the following code:

var assembly = Assembly.LoadFrom( FilePathHere );

I need/want to be able to unload this assembly when i am done.

Thanks for your help.

+14  A: 

You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain.

See Jason Zander's explanation of Why isn't there an Assembly.Unload method?

If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you can unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it.

Philip Rieck
I thought this changed with .Net 3.5?
Derik Whittaker
There are no plans to allow the unload of an assembly from an app domain (I wouldn't expect them to either, it is very hard to do and those that care will use a safer and cleaner workaround). The best you can do is lightweight code gen which Khoth mentioned
ShuggyCoUk
+5  A: 

You can't unload an assembly without unloading the whole AppDomain. Here's why:

  1. You are running that code in the app domain. That means there are potentially call sites and call stacks with addresses in them that are expecting to keep working.

  2. Say you did manage to track all handles and references to already running code by an assembly. Assuming you didn't ngen the code, once you successfully freed up the assembly, you have only freed up the metadata and IL. The JIT'd code is still allocated in the app domain loader heap (JIT'd methods are allocated sequentially in a buffer in the order in which they are called).

  3. The final issue relates to code which has been loaded shared, otherwise more formally know as "domain neutral" (check out /shared on the ngen tool). In this mode, the code for an assembly is generated to be executed from any app domain (nothing hard wired).

It is recommended that you design your application around the application domain boundary naturally, where unload is fully supported.

Mark Cidade
+3  A: 

If you want to have temporary code which can be unloaded afterwards, depending on your needs the DynamicMethod class might do what you want. That doesn't give you classes, though.

Khoth
+2  A: 

you should load your temporary assemblies in another AppDomain and when not in use then you can unload that AppDomain. Its safe and fast

Nipun
A: 

Here is a GOOD example how to compile and run dll during run time and then unload all resources: http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm

GenZiy