private static Assembly RedirectAssemblyLoad()

in src/Common/Commands.Common/PowerBICmdlet.cs [48:100]


        private static Assembly RedirectAssemblyLoad(object sender, ResolveEventArgs args)
        {
            /*
            * Situations Assembly Resolver is used:
            * 
            * The assembly resolver is used to load System.Net.Http due to a bug introduced in .NET Framework and later fixed but causes assembly version mismatch.
            * Assembly resolver was the clear choice as the System.Net.Http package only fixed the issue in PowerShell Core but would fail when running from PowerShell for Windows.
            * 
            * It is used to load MSAL assemblies as the netstandard2.0 (or in MSAL case, netstandard1.3) will throw PlatformNotSupported when used.
            * Both net45 and netcoreapp2.1 are packaged up and placed in an MSAL directory under the module.
            * 
            * Finally it is used to fix mismatches with Newtonsoft.Json.
            * In this situation, it's a best effort because if a very old version of Newtonsoft.Json is loaded and it's contract is incompatible with used in codebase, then we will run into type mismatch errors which we can't handle.
            */
            var requestedAssembly = new AssemblyName(args.Name);
            string executingDirectory = GetExecutingDirectory();

            // Handle MSAL assemblies
            string assemblyFilePath;
            if (requestedAssembly.Name == "Microsoft.Identity.Client" || requestedAssembly.Name == "Microsoft.Identity.Client.Extensions.Msal")
            {
                var libType = IsNetFramework ? "net45" : "netcoreapp2.1";
                assemblyFilePath = Path.Combine(executingDirectory, "MSAL", libType, requestedAssembly.Name + ".dll");
            }
            else
            {
                assemblyFilePath = Path.Combine(executingDirectory, requestedAssembly.Name + ".dll");
            }

            if (File.Exists(assemblyFilePath))
            {
                try
                {
                    return Assembly.LoadFrom(assemblyFilePath);
                }
                catch (Exception)
                {
                    // Ignore as the assembly resolver is meant as a last resort to find an assembly
                }
            }

            // This allows usage of assemblies in the current application domain to be used when a specific version of an assembly wasn't found
            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (asm.FullName.Equals(args.Name))
                {
                    return asm;
                }
            }

            // Return null to indicate the assembly was not found
            return null;
        }