英文:
Using AssemblyLoadContext LoadFromAssemblyPath fails to unload it later
问题
我正在在.NET 7 WPF应用程序中动态加载程序集。
此上下文加载器允许我稍后卸载它(参见 MemoryStream
):
(取自此处:https://github.com/dotnet/runtime/issues/13226)
public class CollectableAssemblyLoadContext : AssemblyLoadContext
{
private bool disposedValue;
public CollectableAssemblyLoadContext(string name) : base(name, true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
public Assembly Load(byte[] rawAssembly)
{
using (var memoryStream = new MemoryStream(rawAssembly))
{
var assembly = LoadFromStream(memoryStream);
return assembly;
}
}
}
但是在卸载时会引发 "不可收集的程序集" 异常:
(取自此处:https://learn.microsoft.com/en-gb/dotnet/core/tutorials/creating-app-with-plugin-support)
public class PluginLoader : AssemblyLoadContext
{
private AssemblyDependencyResolver resolver;
public PluginLoader(string pluginPath)
{
resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
}
为什么会出现这个异常?是设计如此还是我做错了什么?
英文:
I am loading an assembly dynamically at run-time in .net 7 WPF app..
This context loader lets me to unload it later (see the MemoryStream
):
(taken from here: https://github.com/dotnet/runtime/issues/13226)
public class CollectableAssemblyLoadContext : AssemblyLoadContext
{
private bool disposedValue;
public CollectableAssemblyLoadContext(string name) : base(name, true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
public Assembly Load(byte[] rawAssembly)
{
using (var memoryStream = new MemoryStream(rawAssembly))
{
var assembly = LoadFromStream(memoryStream);
return assembly;
}
}
}
And this throws "not collectible assembly" exception on unload:
(taken from here: https://learn.microsoft.com/en-gb/dotnet/core/tutorials/creating-app-with-plugin-support)
public class PluginLoader : AssemblyLoadContext
{
private AssemblyDependencyResolver resolver;
public PluginLoader(string pluginPath)
{
resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
}
Why? Is it by design or am I doing something wrong?
答案1
得分: 0
构造函数应该调用基类,并将标志设置为 true
- 这确保了可收集性:
public PluginLoader(string pluginPath) : base(pluginPath, true)
英文:
The constructor should call base class with flag set to true
- that ensures collectability:
public PluginLoader(string pluginPath) : base(pluginPath, true)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论