0.2.0-dev Download ZIP
50 lines ·2.1 KB Raw
| 1 | using System.Reflection; |
| 2 | using System.Runtime.Loader; |
| 3 | |
| 4 | namespace EvilEngine.Host.Tests; |
| 5 | |
| 6 | public sealed class LoadContextTests |
| 7 | { |
| 8 | private static readonly string Installed = typeof(LoadContextTests).Assembly |
| 9 | .GetCustomAttributes<AssemblyMetadataAttribute>() |
| 10 | .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!; |
| 11 | |
| 12 | [Fact] |
| 13 | public void LoadsAdaptersWhenTheHostIsLoadedOutsideTheDefaultContext() |
| 14 | { |
| 15 | var hostDll = typeof(EngineHost).Assembly.Location; |
| 16 | var context = new Elsewhere(Path.GetDirectoryName(hostDll)!); |
| 17 | try |
| 18 | { |
| 19 | var hostType = context.LoadFromAssemblyPath(hostDll).GetType(typeof(EngineHost).FullName!)!; |
| 20 | Assert.NotSame(typeof(EngineHost), hostType); |
| 21 | var host = Activator.CreateInstance(hostType, [null, null])!; |
| 22 | var adapters = hostType.GetProperty(nameof(EngineHost.Adapters))!.GetValue(host)!; |
| 23 | adapters.GetType().GetMethod(nameof(AdapterHost.LoadAll))!.Invoke(adapters, [new[] { Installed }, null]); |
| 24 | |
| 25 | var problems = (IEnumerable<object>)adapters.GetType().GetProperty(nameof(AdapterHost.Problems))! |
| 26 | .GetValue(adapters)!; |
| 27 | var loaded = (IEnumerable<object>)adapters.GetType().GetProperty(nameof(AdapterHost.Loaded))! |
| 28 | .GetValue(adapters)!; |
| 29 | Assert.Empty(problems.Select(problem => problem.ToString())); |
| 30 | Assert.Contains("gmod", loaded.Select(adapter => |
| 31 | { |
| 32 | var manifest = adapter.GetType().GetProperty(nameof(LoadedAdapter.Manifest))!.GetValue(adapter)!; |
| 33 | return (string)manifest.GetType().GetProperty(nameof(AdapterManifest.Id))!.GetValue(manifest)!; |
| 34 | })); |
| 35 | } |
| 36 | finally |
| 37 | { |
| 38 | context.Unload(); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | private sealed class Elsewhere(string folder) : AssemblyLoadContext("elsewhere", true) |
| 43 | { |
| 44 | protected override Assembly? Load(AssemblyName assemblyName) |
| 45 | { |
| 46 | var path = Path.Combine(folder, $"{assemblyName.Name}.dll"); |
| 47 | return File.Exists(path) ? LoadFromAssemblyPath(path) : null; |
| 48 | } |
| 49 | } |
| 50 | } |