|
| 1 | +using System.Diagnostics.CodeAnalysis; |
| 2 | +using System.IO; |
| 3 | +using System.Reflection; |
| 4 | +using System.Runtime.Loader; |
| 5 | + |
| 6 | +namespace PSCompression.Shared; |
| 7 | + |
| 8 | +[ExcludeFromCodeCoverage] |
| 9 | +public sealed class LoadContext : AssemblyLoadContext |
| 10 | +{ |
| 11 | + private static LoadContext? _instance; |
| 12 | + |
| 13 | + private readonly static object s_sync = new(); |
| 14 | + |
| 15 | + private readonly Assembly _thisAssembly; |
| 16 | + |
| 17 | + private readonly AssemblyName _thisAssemblyName; |
| 18 | + |
| 19 | + private readonly Assembly _moduleAssembly; |
| 20 | + |
| 21 | + private readonly string _assemblyDir; |
| 22 | + |
| 23 | + private LoadContext(string mainModulePathAssemblyPath) |
| 24 | + : base(name: "PSCompression", isCollectible: false) |
| 25 | + { |
| 26 | + _assemblyDir = Path.GetDirectoryName(mainModulePathAssemblyPath) ?? ""; |
| 27 | + _thisAssembly = typeof(LoadContext).Assembly; |
| 28 | + _thisAssemblyName = _thisAssembly.GetName(); |
| 29 | + _moduleAssembly = LoadFromAssemblyPath(mainModulePathAssemblyPath); |
| 30 | + } |
| 31 | + |
| 32 | + protected override Assembly? Load(AssemblyName assemblyName) |
| 33 | + { |
| 34 | + if (AssemblyName.ReferenceMatchesDefinition(_thisAssemblyName, assemblyName)) |
| 35 | + { |
| 36 | + return _thisAssembly; |
| 37 | + } |
| 38 | + |
| 39 | + string asmPath = Path.Join(_assemblyDir, $"{assemblyName.Name}.dll"); |
| 40 | + if (File.Exists(asmPath)) |
| 41 | + { |
| 42 | + return LoadFromAssemblyPath(asmPath); |
| 43 | + } |
| 44 | + |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + public static Assembly Initialize() |
| 49 | + { |
| 50 | + LoadContext? instance = _instance; |
| 51 | + if (instance is not null) |
| 52 | + { |
| 53 | + return instance._moduleAssembly; |
| 54 | + } |
| 55 | + |
| 56 | + lock (s_sync) |
| 57 | + { |
| 58 | + if (_instance is not null) |
| 59 | + { |
| 60 | + return _instance._moduleAssembly; |
| 61 | + } |
| 62 | + |
| 63 | + string assemblyPath = typeof(LoadContext).Assembly.Location; |
| 64 | + string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); |
| 65 | + string moduleName = assemblyName[..^7]; |
| 66 | + string modulePath = Path.Combine( |
| 67 | + Path.GetDirectoryName(assemblyPath)!, |
| 68 | + $"{moduleName}.dll"); |
| 69 | + |
| 70 | + return new LoadContext(modulePath)._moduleAssembly; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments