A .NET desktop host loads customer plugins into a collectible AssemblyLoadContext and calls Unload, yet the plugins never leave memory; why, and how do you prove it?
answer
- unload is cooperative
- it waits for references
- host-side caches and events
- weak reference plus collections
- shared contracts stay in Default
basics
~20 sAssemblyLoadContext.Unload only starts a cooperative unload; the context is freed once nothing references it or anything loaded in it. A cached plugin object, Type, delegate, event handler or running thread keeps it alive; a WeakReference checked after forced collections proves it.
solid answer
~50 sA collectible `AssemblyLoadContext` (created with `isCollectible: true`) can be unloaded, but `Unload()` only **initiates** it: the context, its assemblies and their code are freed by the garbage collector once nothing outside the context references the context, an assembly, a type, a method or an object from it. The usual culprits sit in the host: a cache holding a plugin instance, a `Type` or `MethodInfo` kept for later, a delegate or event subscription the plugin registered with a host event, a timer or thread still running plugin code, or a plugin assembly loaded through `Assembly.LoadFrom`, which goes into the default context and never unloads. To prove it, create the context inside a non-inlined method, keep only a `WeakReference` to it, call `Unload()`, then run `GC.Collect()` and `GC.WaitForPendingFinalizers()` in a loop and check `IsAlive`; if it stays alive, a GC-root analysis of a memory dump shows the path that holds it.
code
csharp · 35 lines#:property PublishAot=false
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
string path = typeof(Host).Assembly.Location; // load this app's own dll again as the "plugin"
WeakReference clean = Host.RunPlugin(path, keep: false);
WeakReference leaky = Host.RunPlugin(path, keep: true);
for (int i = 0; i < 10 && (clean.IsAlive || leaky.IsAlive); i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Console.WriteLine($"context without held references alive: {clean.IsAlive}");
Console.WriteLine($"context whose object the host kept alive: {leaky.IsAlive}");
static class Host
{
public static object? Cache; // a host-side field holding a plugin object
[MethodImpl(MethodImplOptions.NoInlining)]
public static WeakReference RunPlugin(string path, bool keep)
{
var alc = new AssemblyLoadContext("plugin", isCollectible: true);
Assembly asm = alc.LoadFromAssemblyPath(path);
object plugin = Activator.CreateInstance(asm.GetType("PricingPlugin")!)!;
if (keep) Cache = plugin;
alc.Unload(); // only starts the unload
return new WeakReference(alc);
}
}
public class PricingPlugin { public override string ToString() => "PricingPlugin"; }go deeper
Know that a plugin host creates its own AssemblyLoadContext, and that only one created as collectible can be unloaded.
Explain that Unload only starts the process and that the garbage collector finishes it once no references remain, and list the references that typically remain.
Prove a leak with a WeakReference and forced collections, find the root with a dump, and fix host-side caches, event subscriptions and Assembly.LoadFrom misuse.
Design the plugin boundary so unloading is reliable: contracts in the default context, data rather than plugin objects across the boundary, and an unload test in the host's suite.
## What AssemblyLoadContext gives a plugin host Every .NET process has `AssemblyLoadContext.Default`, which loads the app and its static dependencies. A host that loads code it did not ship with, such as customer plugins, creates its own contexts: - **Isolation by name**: each context holds one version of an assembly per simple name, so two plugins can depend on different versions of the same library. - **Unloading**: a context created with `new AssemblyLoadContext(name, isCollectible: true)` can be unloaded, together with every assembly loaded into it. The default context is not collectible (`AssemblyLoadContext.Default.IsCollectible` is `false`), and calling `Unload()` on a non-collectible context throws `InvalidOperationException` with "Cannot unload non-collectible AssemblyLoadContext." ## What Unload actually does Unloading is **cooperative**, not forced: 1. `Unload()` marks the context as unloading and raises its `Unloading` event. Further loads into it throw `InvalidOperationException`: "AssemblyLoadContext is unloading or was already unloaded." 2. Nothing is freed yet. The runtime cannot tear down code that something may still call. 3. The garbage collector frees the context, its assemblies and their compiled code only after no live reference reaches any of them. So "Unload did nothing" almost always means "something still references the context". ## What keeps a context alive Any strong reference from outside the context to something inside it is enough: - an **object** created from a plugin type, held in a host cache, a dictionary, a DI container or a static field; - a **`Type`, `MethodInfo` or `Assembly`** object the host kept for later reflection; - a **delegate** pointing at plugin code: a callback, a host event the plugin subscribed to, or a `Func` stored in a registry; - a **thread, timer or pending task** still executing plugin code, because a stack frame is a root; - a **`GCHandle`** or native callback the plugin allocated and never freed; - a reference to the context object itself. A separate trap: `Assembly.LoadFrom` loads into the **default** context, so a plugin loaded that way can never unload. ## Proving whether it unloaded Make the test deterministic: 1. Create the context, load and run the plugin inside a method marked `[MethodImpl(MethodImplOptions.NoInlining)]`, so no local in the caller keeps references alive. 2. Return only a `WeakReference` to the context. 3. Call `Unload()`, then loop a few times over `GC.Collect()` and `GC.WaitForPendingFinalizers()`. 4. Check `weakRef.IsAlive`. If it stays `true`, take a memory dump and ask the dump tooling for the GC roots of the context object, which names the static field, event or thread holding it; capturing and reading dumps is covered with .NET's diagnostics tools. ## Designing a host where unload works - **Share contracts through the default context.** Put the plugin interface in a contract assembly the host references. A custom context's `Load` override returns `null` for it, so it falls back to the default context and host and plugin agree on one `IPlugin` type. - **Resolve plugin dependencies with `AssemblyDependencyResolver`.** Constructed with the plugin's path, it reads the plugin's `.deps.json`; `ResolveAssemblyToPath` and `ResolveUnmanagedDllToPath` feed the `Load` and `LoadUnmanagedDll` overrides. - **Hand data across the boundary, not plugin objects.** Return host types or primitives, and keep no plugin instances in host caches. - **Make subscriptions symmetric.** Every event a plugin subscribes to must be unsubscribed, and timers stopped, before `Unload()`. ## Debugging which context owns what - `AssemblyLoadContext.GetLoadContext(assembly)` returns the context that loaded an assembly, and its `Name` (the string passed to the constructor) tells you whether a plugin type came from the plugin context or slipped into the default one. - The `Unloading` event, raised at the start of `Unload()`, is the place for the plugin to stop its timers and unsubscribe from host events. - `AssemblyLoadContext.All` enumerates the live contexts, so a host can report how many plugin contexts are still alive after unloading them. - Keep the unload test in the host's automated suite: a regression that adds a host-side cache shows up as a context that is still alive. ## The type-identity trap If both the host and the plugin context load their own copy of the contract assembly, the two `IPlugin` types are different, and casts fail with a message like "Object of type 'IsolatedType' cannot be converted to type 'IsolatedType'." Loading the shared contract only in the default context avoids this.
- Why must the plugin contract assembly be loaded only in the default context?A type's identity includes the assembly instance it came from. If the plugin context loads its own copy of the contract assembly, its `IPlugin` is a different type from the host's, and casts fail with a confusing 'cannot be converted to type' error naming the same type twice. Returning `null` from the custom context's `Load` for the contract lets it fall back to the default context, so both sides share one type.
- What is AssemblyDependencyResolver for in a plugin host?It is constructed with the plugin's main assembly path and reads that plugin's `.deps.json`, so `ResolveAssemblyToPath` and `ResolveUnmanagedDllToPath` return the files the plugin was built against, including NuGet dependencies and native libraries. A custom context calls it from its `Load` and `LoadUnmanagedDll` overrides, letting each plugin bring its own dependency versions.
- Can a Native AOT host load plugins this way?No. Native AOT has no dynamic loading, so `LoadFromAssemblyPath` cannot bring new IL into the process. A plugin host that loads customer assemblies at run time stays on the JIT, possibly with ReadyToRun for its own code.
A collectible context is a library book that can only go back on the shelf once every borrower has returned it. Unload is the recall notice; the book stays checked out while any copy of the borrowing slip, an object, a Type or a delegate, is still in someone's pocket.
- Calling Unload frees the plugin's memory immediately.
- Any AssemblyLoadContext can be unloaded, including the default one.
- Assembly.LoadFrom puts a plugin somewhere it can later be unloaded.
- Keeping only a Type object of a plugin cannot keep it loaded.
- Each plugin context should load its own copy of the contract assembly.