| |
| |
|
|
| using System; |
| using System.Collections.Generic; |
| using System.IO; |
| using System.Management.Automation; |
| using System.Reflection; |
| using System.Runtime.Loader; |
|
|
| namespace Test.Isolated.Init |
| { |
| internal sealed class CustomLoadContext : AssemblyLoadContext |
| { |
| private readonly string _dependencyDirPath; |
|
|
| public CustomLoadContext(string dependencyDirPath) |
| : base("MyCustomALC", isCollectible: false) |
| { |
| _dependencyDirPath = dependencyDirPath; |
| } |
|
|
| protected override Assembly Load(AssemblyName assemblyName) |
| { |
| |
| |
| string assemblyPath = Path.Combine(_dependencyDirPath, $"{assemblyName.Name}.dll"); |
|
|
| if (File.Exists(assemblyPath)) |
| { |
| |
| |
| return LoadFromAssemblyPath(assemblyPath); |
| } |
|
|
| |
| return null; |
| } |
| } |
|
|
| public class Init : IModuleAssemblyInitializer, IModuleAssemblyCleanup |
| { |
| private static readonly CustomLoadContext s_context; |
| private static readonly HashSet<string> s_moduleAssemblies; |
|
|
| static Init() |
| { |
| string dependencyDirPath = Path.Combine(Path.GetDirectoryName(typeof(Init).Assembly.Location), "Dependencies"); |
| s_context = new CustomLoadContext(dependencyDirPath); |
| s_moduleAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase) |
| { |
| "Test.Isolated.Nested", |
| "Test.Isolated.Root" |
| }; |
| } |
|
|
| public void OnImport() |
| { |
| |
| AssemblyLoadContext.Default.Resolving += ResolveAlcEngine; |
| } |
|
|
| public void OnRemove(PSModuleInfo psModuleInfo) |
| { |
| |
| AssemblyLoadContext.Default.Resolving -= ResolveAlcEngine; |
| } |
|
|
| private static Assembly ResolveAlcEngine(AssemblyLoadContext defaultAlc, AssemblyName assemblyToResolve) |
| { |
| |
| if (s_moduleAssemblies.Contains(assemblyToResolve.Name)) |
| { |
| |
| |
| return s_context.LoadFromAssemblyName(assemblyToResolve); |
| } |
|
|
| |
| return null; |
| } |
| } |
| } |
|
|