How to unload an assembly from the primary AppDomain?

Derik Whittaker picture Derik Whittaker · Sep 23, 2008 · Viewed 33.7k times · Source

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.

Answer

Philip Rieck picture Philip Rieck · Sep 23, 2008

For .net versions core 3.0 and later:

You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See AssemblyLoadContext, or this tutorial that simulates loading a plugin then unloading it.

For .net versions before .net core 3, including netframework 4 and lower

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.