I'm trying to get dynamic assembly loading to work in .NET Core 3.1, and have been following microsoft's guide on creating a custom AssemblyLoadContext. The assembly loading seems to be successfull however as soon i try to actually retrieve a type by using GetTypes() i get this error about System.Runtime being in use:
"Unable to load one or more of the requested types.Could not load file or assembly 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Process cannot access file because it is being used by another process. (0x80070020)
I've been looking for an answer to this issue but haven't found anything coming close to this via google yet, so i really hope someone has an idea on what i could be doing wrong here.
Three projects are involved which are set up as follows:
The custom AssemblyLoadContext looks like this:
internal class RainyServersExtensionLoadContext : AssemblyLoadContext
{
private AssemblyDependencyResolver _resolver;
private Assembly _assembly;
private readonly string _assemblyLocation;
public RainyServersExtensionLoadContext(string applicationDirectory, string fileName)
{
_assemblyLocation = Path.Combine(applicationDirectory, "CoreExtensions", fileName);
_resolver = new AssemblyDependencyResolver(_assemblyLocation);
}
internal Assembly GetAssembly()
{
return _assembly;
}
internal Assembly LoadFromAssemblyName(string name)
{
var assemblyName = new AssemblyName(name);
return LoadFromAssemblyName(assemblyName);
}
protected override Assembly Load(AssemblyName assemblyName)
{
string path = _resolver.ResolveAssemblyToPath(assemblyName);
if (!string.IsNullOrEmpty(path))
{
_assembly = LoadFromAssemblyPath(path);
return _assembly;
}
if (File.Exists(_assemblyLocation))
{
var stream = File.Open(_assemblyLocation, FileMode.Open);
_assembly = LoadFromStream(stream);
return _assembly;
}
return null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (!string.IsNullOrEmpty(libraryPath))
return LoadUnmanagedDllFromPath(libraryPath);
return IntPtr.Zero;
}
}
The dll file itself can be found and is loaded into a System.Reflection.Assembly object as can be seen in this screenshot and this screenshot.
However as soon as i try to execte the Assembly object's GetTypes method i get the above error about System.Runtime being in use.
Anyone have an idea how i might be able to fix this?
When you use this:
var stream = File.Open(_assemblyLocation, FileMode.Open);
you are opening it for read/write. Documentation says: Opens a FileStream on the specified path with read/write access with no sharing.
Try changing it to:
var stream = File.Open(_assemblyLocation, FileMode.Open, FileAccess.Read);
Which means you simply want to read and read only.
User contributions licensed under CC BY-SA 3.0