using System.Reflection; using System.Runtime.Loader; namespace EvilEngine.Host.Tests; public sealed class LoadContextTests { private static readonly string Installed = typeof(LoadContextTests).Assembly .GetCustomAttributes() .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!; [Fact] public void LoadsAdaptersWhenTheHostIsLoadedOutsideTheDefaultContext() { var hostDll = typeof(EngineHost).Assembly.Location; var context = new Elsewhere(Path.GetDirectoryName(hostDll)!); try { var hostType = context.LoadFromAssemblyPath(hostDll).GetType(typeof(EngineHost).FullName!)!; Assert.NotSame(typeof(EngineHost), hostType); var host = Activator.CreateInstance(hostType, [null, null])!; var adapters = hostType.GetProperty(nameof(EngineHost.Adapters))!.GetValue(host)!; adapters.GetType().GetMethod(nameof(AdapterHost.LoadAll))!.Invoke(adapters, [new[] { Installed }, null]); var problems = (IEnumerable)adapters.GetType().GetProperty(nameof(AdapterHost.Problems))! .GetValue(adapters)!; var loaded = (IEnumerable)adapters.GetType().GetProperty(nameof(AdapterHost.Loaded))! .GetValue(adapters)!; Assert.Empty(problems.Select(problem => problem.ToString())); Assert.Contains("gmod", loaded.Select(adapter => { var manifest = adapter.GetType().GetProperty(nameof(LoadedAdapter.Manifest))!.GetValue(adapter)!; return (string)manifest.GetType().GetProperty(nameof(AdapterManifest.Id))!.GetValue(manifest)!; })); } finally { context.Unload(); } } private sealed class Elsewhere(string folder) : AssemblyLoadContext("elsewhere", true) { protected override Assembly? Load(AssemblyName assemblyName) { var path = Path.Combine(folder, $"{assemblyName.Name}.dll"); return File.Exists(path) ? LoadFromAssemblyPath(path) : null; } } }