在运行时使用 System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName 加载第三方 dll 时出现问题

问题描述 投票:0回答:1

在我的 .NET Core 6.0 WebAPI 项目中,我尝试使用

System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName
加载第三方 dll。

我经常在加载第三方 dll 时看到,当我的 WebAPI 空闲一段时间时,它会被卸载。当我重新启动 IIS 时,它工作正常。频繁卸载dll可能是什么原因?

这是使用

System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName()
的已知问题吗?如果是这样,我该如何解决它?

或者,除了

System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName
之外,还有其他DLL我可以使用吗?

我正在使用这段代码来加载汇编文件:

public Assembly LoadPlugin(string assemblyPath)
{
    CustomAssemblyLoadContext loadContext = new CustomAssemblyLoadContext(assemblyPath);
    return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(assemblyPath)));
}
c# asp.net-core dllimport webapi assemblyloadcontext
1个回答
0
投票

不确定如何自定义

AssemblyLoadContext
,但默认情况下
AssemblyLoadContext
配置,它包含
isCollectible
,这是错误的,它会阻止卸载:

var assemblyLoadContext = new AssemblyLoadContext(null, isCollectible: false);

如果默认设置仍然不起作用,您可以 尝试确保主动使用已加载程序集中的类型或对象:

var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("YourAssemblyName"));

// Create an instance of a type from the assembly to hold a reference
var instance = assembly.CreateInstance("Namespace.ClassName");
© www.soinside.com 2019 - 2024. All rights reserved.