ModuleInit.cs (2153B)
1 // ----------------------------------------------------------------------------- 2 // <copyright file="ModuleInit.cs" company="Microsoft Corporation"> 3 // Copyright (c) Microsoft Corporation. Licensed under the MIT License. 4 // </copyright> 5 // ----------------------------------------------------------------------------- 6 7 namespace Microsoft.WinGet.Resolver 8 { 9 using System; 10 using System.Collections.Generic; 11 using System.Linq; 12 using System.Management.Automation; 13 using System.Runtime.InteropServices; 14 15 #if !POWERSHELL_WINDOWS 16 using System.Runtime.Loader; 17 #else 18 using Microsoft.WinGet.Client.Cmdlets.Resolver; 19 #endif 20 21 /// <summary> 22 /// Initialization class for this module. 23 /// </summary> 24 public class ModuleInit : IModuleAssemblyInitializer, IModuleAssemblyCleanup 25 { 26 private static readonly IEnumerable<Architecture> ValidArchs = new Architecture[] { Architecture.X86, Architecture.X64, Architecture.Arm64 }; 27 28 /// <inheritdoc/> 29 public void OnImport() 30 { 31 var arch = RuntimeInformation.ProcessArchitecture; 32 if (!ValidArchs.Contains(arch)) 33 { 34 throw new NotSupportedException(arch.ToString()); 35 } 36 37 #if !POWERSHELL_WINDOWS 38 AssemblyLoadContext.Default.Resolving += WinGetAssemblyLoadContext.ResolvingHandler; 39 #else 40 // If we really need to avoid dependency conflicts, we could create a custom domain and handle the serialization boundaries. 41 // PowerShell doesn't recommended because its complications. 42 AppDomain currentDomain = AppDomain.CurrentDomain; 43 currentDomain.AssemblyResolve += WinGetAppDomain.Handler; 44 #endif 45 } 46 47 /// <inheritdoc/> 48 public void OnRemove(PSModuleInfo module) 49 { 50 #if !POWERSHELL_WINDOWS 51 AssemblyLoadContext.Default.Resolving -= WinGetAssemblyLoadContext.ResolvingHandler; 52 #else 53 AppDomain currentDomain = AppDomain.CurrentDomain; 54 currentDomain.AssemblyResolve -= WinGetAppDomain.Handler; 55 #endif 56 } 57 } 58 }