| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="PluginLoadContext.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System.Reflection; |
| | | 8 | | using System.Runtime.Loader; |
| | | 9 | | |
| | | 10 | | namespace MyNet.Utilities.Plugins; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// An isolated <see cref="AssemblyLoadContext"/> used to load a single plugin assembly |
| | | 14 | | /// and its dependencies without polluting the default load context. |
| | | 15 | | /// Each plugin subdirectory gets its own <see cref="PluginLoadContext"/> so that |
| | | 16 | | /// different plugins can reference different versions of the same dependency. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="pluginPath"> |
| | | 19 | | /// The full path to the plugin DLL. The <see cref="AssemblyDependencyResolver"/> |
| | | 20 | | /// uses this path to locate sibling dependency assemblies. |
| | | 21 | | /// </param> |
| | 0 | 22 | | internal sealed class PluginLoadContext(string pluginPath) : AssemblyLoadContext |
| | | 23 | | { |
| | 0 | 24 | | private readonly AssemblyDependencyResolver _resolver = new(pluginPath); |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Resolves the managed assembly by probing the plugin's own dependency graph first. |
| | | 28 | | /// Returns <c>null</c> to fall back to the default context when the assembly is not |
| | | 29 | | /// part of the plugin (e.g., shared framework assemblies). |
| | | 30 | | /// </summary> |
| | | 31 | | protected override Assembly? Load(AssemblyName assemblyName) |
| | | 32 | | { |
| | 0 | 33 | | var assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); |
| | 0 | 34 | | return assemblyPath != null ? LoadFromAssemblyPath(assemblyPath) : null; |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Resolves a native (unmanaged) library by probing the plugin's dependency graph. |
| | | 39 | | /// Returns <see cref="nint.Zero"/> to fall back to the OS search when not found. |
| | | 40 | | /// </summary> |
| | | 41 | | protected override nint LoadUnmanagedDll(string unmanagedDllName) |
| | | 42 | | { |
| | 0 | 43 | | var libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); |
| | 0 | 44 | | return libraryPath != null ? LoadUnmanagedDllFromPath(libraryPath) : nint.Zero; |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | |