|  | 
|  | 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. | 
|  | 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. | 
|  | 3 | + | 
|  | 4 | +namespace Microsoft.Windows.CsWin32 | 
|  | 5 | +{ | 
|  | 6 | +    using System; | 
|  | 7 | +    using System.Collections.Generic; | 
|  | 8 | +    using System.IO; | 
|  | 9 | +    using System.Linq; | 
|  | 10 | +    using System.Reflection; | 
|  | 11 | +    using System.Runtime.CompilerServices; | 
|  | 12 | +    using System.Runtime.InteropServices; | 
|  | 13 | + | 
|  | 14 | +    internal static class BindingRedirects | 
|  | 15 | +    { | 
|  | 16 | +        private static readonly string SourceGeneratorAssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); | 
|  | 17 | +        private static readonly Lazy<Dictionary<string, string>> LocalAssemblies; | 
|  | 18 | + | 
|  | 19 | +        static BindingRedirects() | 
|  | 20 | +        { | 
|  | 21 | +            LocalAssemblies = new Lazy<Dictionary<string, string>>( | 
|  | 22 | +                () => Directory.GetFiles(SourceGeneratorAssemblyDirectory, "*.dll").ToDictionary(Path.GetFileNameWithoutExtension, StringComparer.OrdinalIgnoreCase)); | 
|  | 23 | +        } | 
|  | 24 | + | 
|  | 25 | +        private static bool IsNetFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); | 
|  | 26 | + | 
|  | 27 | +#pragma warning disable CA2255 // The 'ModuleInitializer' attribute should not be used in libraries | 
|  | 28 | +        [ModuleInitializer] | 
|  | 29 | +#pragma warning restore CA2255 // The 'ModuleInitializer' attribute should not be used in libraries | 
|  | 30 | +        internal static void ApplyBindingRedirects() | 
|  | 31 | +        { | 
|  | 32 | +            if (IsNetFramework) | 
|  | 33 | +            { | 
|  | 34 | +                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; | 
|  | 35 | +            } | 
|  | 36 | +        } | 
|  | 37 | + | 
|  | 38 | +        private static Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) | 
|  | 39 | +        { | 
|  | 40 | +            AssemblyName expected = new(args.Name); | 
|  | 41 | +            if (LocalAssemblies.Value.TryGetValue(expected.Name, out string? path)) | 
|  | 42 | +            { | 
|  | 43 | +                AssemblyName actual = AssemblyName.GetAssemblyName(path); | 
|  | 44 | +                if (actual.Version >= expected.Version) | 
|  | 45 | +                { | 
|  | 46 | +                    return Assembly.LoadFile(path); | 
|  | 47 | +                } | 
|  | 48 | +            } | 
|  | 49 | + | 
|  | 50 | +            return null; | 
|  | 51 | +        } | 
|  | 52 | +    } | 
|  | 53 | +} | 
0 commit comments