So I have a program that I want to load an assembly and in the Load method, some assemblies do not seem to be loaded and my methods are not returned. I want to load the assembly, retrieve all test methods, and unload it because I want to then reload it a second time later on in the program.
Also, unload doesn't seem to free the assembly. I try building the referenced DLL after I unload and I get that "...being used by another process. The file is locked by "MyProject""
public class TestAssemblyLoadContext : AssemblyLoadContext
{
private AssemblyDependencyResolver _resolver;
public TestAssemblyLoadContext(string pluginPath) : base(isCollectible: true)
{
_resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName name)
{
string assemblyPath = _resolver.ResolveAssemblyToPath(name);
if (assemblyPath != null)
{
Console.WriteLine($"Loading assembly {assemblyPath} into the TestAssemblyLoadContext");
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
}
And I call it here and unload it. I want to call this method twice to compare methods in different git branches and figure out some info in the methods.
private static IOrderedEnumerable<MethodInfo> GetMethods(string assemblyPath)
{
var alc = new TestAssemblyLoadContext(assemblyPath);
Assembly assembly = alc.LoadFromAssemblyPath(assemblyPath);
var methods = assembly.GetTypes()
.SelectMany(t => t.GetMethods())
.Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0 || m.GetCustomAttributes(typeof(TestCaseAttribute), false).Length > 0)
.OrderBy(tm => tm.DeclaringType.FullName[..tm.DeclaringType.FullName.LastIndexOf(".")]);
// Assembly is still locked and can't build as an example
alc.Unload();
return methods;
}