| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using System.Reflection; |
| | | 3 | | |
| | | 4 | | namespace NexusLabs.Needlr.Injection.Reflection.Loaders; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Assembly loader that loads assemblies from disk based on file name matching. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <remarks> |
| | | 10 | | /// This loader is not compatible with NativeAOT or trimming. For AOT scenarios, |
| | | 11 | | /// use GeneratedAssemblyProvider from NexusLabs.Needlr.Injection.SourceGen instead. |
| | | 12 | | /// </remarks> |
| | | 13 | | [RequiresUnreferencedCode("FileMatchAssemblyLoader uses Assembly.LoadFrom which is not AOT-compatible. Use GeneratedAsse |
| | | 14 | | public sealed class FileMatchAssemblyLoader : IAssemblyLoader |
| | | 15 | | { |
| | | 16 | | private readonly IReadOnlyList<string> _directories; |
| | | 17 | | private readonly Predicate<string> _fileFilter; |
| | | 18 | | |
| | 396 | 19 | | public FileMatchAssemblyLoader( |
| | 396 | 20 | | IReadOnlyList<string> directories, |
| | 396 | 21 | | Predicate<string>? fileFilter) |
| | | 22 | | { |
| | 396 | 23 | | ArgumentNullException.ThrowIfNull(directories); |
| | 395 | 24 | | ArgumentNullException.ThrowIfNull(fileFilter); |
| | | 25 | | |
| | 394 | 26 | | _directories = directories; |
| | 394 | 27 | | _fileFilter = fileFilter; |
| | 394 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public IReadOnlyList<Assembly> LoadAssemblies( |
| | | 32 | | bool continueOnAssemblyError) |
| | | 33 | | { |
| | 311 | 34 | | var sourceAssemblies = _directories |
| | 311 | 35 | | .SelectMany(Directory.GetFiles) |
| | 311 | 36 | | .Where(x => |
| | 311 | 37 | | { |
| | 19124 | 38 | | var fileName = Path.GetFileName(x); |
| | 19124 | 39 | | return _fileFilter.Invoke(fileName); |
| | 311 | 40 | | }) |
| | 311 | 41 | | .Select(p => |
| | 311 | 42 | | { |
| | 311 | 43 | | try |
| | 311 | 44 | | { |
| | 636 | 45 | | return Assembly.LoadFrom(p); |
| | 311 | 46 | | } |
| | 3 | 47 | | catch (Exception ex) |
| | 311 | 48 | | { |
| | 3 | 49 | | if (continueOnAssemblyError) |
| | 311 | 50 | | { |
| | 2 | 51 | | return null; |
| | 311 | 52 | | } |
| | 311 | 53 | | else |
| | 311 | 54 | | { |
| | 1 | 55 | | throw new InvalidOperationException($"Failed to load assembly from path: {p}", ex); |
| | 311 | 56 | | } |
| | 311 | 57 | | } |
| | 635 | 58 | | }) |
| | 635 | 59 | | .Where(x => x != null) |
| | 311 | 60 | | .Cast<Assembly>() |
| | 311 | 61 | | .ToArray(); |
| | 309 | 62 | | return sourceAssemblies; |
| | | 63 | | } |
| | | 64 | | } |