I've been having a hard time unloading an assembly loaded as an application part. The assembly is loaded in a collectible load context, but when I try to unload it I can see in the modules window it's never been removed. I assume there is some reference left, which prevents the load context to unload. I unload the context as suggested in the MS docs:
var weakRef = new WeakReference(context, trackResurrection: true);
context.Unload();
for (int i = 0; weakRef.IsAlive && (i < 10); i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
This is how I remove the application part:
partManager.ApplicationParts.Remove(applicationPart);
CustomActionDescriptorChangeProvider.Instance.HasChanged = true;
CustomActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
I can see that the ActionDescriptionCollection
updates and the actions from the unloaded application part are removed.
I inspected pretty much all cache services but I did not notice any references to the unloaded assembly.
The load context unloads correctly if I do not use the assembly as an application part.
I also examined the heap with Windbg but I couldn't find any references to the assembly in question.
Does anyone have any idea where to look for a leftover reference?