Reputation: 1
In my .NET Core 6.0 WebAPI project, I am trying to load third party dlls using System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName
.
Frequently I see while loading the third party dlls it gets unloaded when my WebAPI is idle for sometime. When I restart IIS it works fine. What could be the possibilities of unloading dll frequently?
Is this a known issue using System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName()
? If so, how can I work around it?
Alternatively, is there any DLL other than System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName
I can use?
I am using this piece of code to load the assembly file:
public Assembly LoadPlugin(string assemblyPath)
{
CustomAssemblyLoadContext loadContext = new CustomAssemblyLoadContext(assemblyPath);
return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(assemblyPath)));
}
Upvotes: 0
Views: 232
Reputation: 36715
Not sure how do you custom the AssemblyLoadContext
, but by default AssemblyLoadContext
configuration, it contains isCollectible
which is false and it prevents unloading:
var assemblyLoadContext = new AssemblyLoadContext(null, isCollectible: false);
If the default setting is still not working, you can try to ensure actively uses types or objects from the loaded assembly:
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");
Upvotes: 0