using System.Reflection; using System.Runtime.Loader; namespace MiniTestRunner; /// /// Provides a custom for loading test assemblies in isolation. /// Supports resolving managed and unmanaged dependencies using . /// /// The path to the plugin or test assembly to load. /// Indicates whether the load context is collectible (can be unloaded). sealed class TestLoadContext(string pluginPath, bool collectible = true) : AssemblyLoadContext(name: pluginPath, isCollectible: collectible) { private readonly AssemblyDependencyResolver resolver = new(pluginPath); /// /// Resolves and loads managed assemblies from the specified plugin path. /// Falls back to the default context if the assembly is already loaded. /// /// The name of the assembly to load. /// The loaded , or null if not found. protected override Assembly? Load(AssemblyName assemblyName) { var assemblyInDefaultContext = Default.Assemblies .FirstOrDefault(assembly => assembly.FullName == assemblyName.FullName); if (assemblyInDefaultContext is not null) { return assemblyInDefaultContext; } var assemblyPath = this.resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) { return this.LoadFromAssemblyPath(assemblyPath); } return null; } /// /// Resolves and loads unmanaged DLLs from the specified plugin path. /// /// The name of the unmanaged DLL to load. /// A pointer to the loaded unmanaged DLL, or if not found. protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var libraryPath = this.resolver.ResolveUnmanagedDllToPath(unmanagedDllName); if (libraryPath != null) { return this.LoadUnmanagedDllFromPath(libraryPath); } return IntPtr.Zero; } }