-
Notifications
You must be signed in to change notification settings - Fork 420
/
AssemblyLoader.cs
95 lines (83 loc) · 2.96 KB
/
AssemblyLoader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis;
namespace OmniSharp.Services
{
internal class AssemblyLoader : IAssemblyLoader
{
private static readonly ConcurrentDictionary<string, Assembly> AssemblyCache = new ConcurrentDictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
private readonly ILogger _logger;
public AssemblyLoader(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<AssemblyLoader>();
}
public Assembly Load(AssemblyName name)
{
Assembly result = null;
try
{
result = Assembly.Load(name);
_logger.LogTrace($"Assembly loaded: {name}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to load assembly: {name}");
}
return result;
}
public IReadOnlyList<Assembly> LoadAllFrom(string folderPath)
{
if (string.IsNullOrWhiteSpace(folderPath)) return Array.Empty<Assembly>();
try
{
var assemblies = new List<Assembly>();
foreach (var filePath in Directory.EnumerateFiles(folderPath, "*.dll"))
{
var assembly = LoadFrom(filePath);
if (assembly != null)
{
assemblies.Add(assembly);
}
}
return assemblies;
}
catch (Exception ex)
{
_logger.LogError(ex, $"An error occurred when attempting to access '{folderPath}'.");
return Array.Empty<Assembly>();
}
}
public Assembly LoadFrom(string assemblyPath, bool dontLockAssemblyOnDisk = false)
{
if (string.IsNullOrWhiteSpace(assemblyPath)) return null;
if (!AssemblyCache.TryGetValue(assemblyPath, out var assembly))
{
try
{
if (dontLockAssemblyOnDisk)
{
var bytes = File.ReadAllBytes(assemblyPath);
assembly = Assembly.Load(bytes);
}
else
{
assembly = Assembly.LoadFrom(assemblyPath);
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to load assembly from path: {assemblyPath}");
return assembly;
}
AssemblyCache.AddOrUpdate(assemblyPath, assembly, (k, v) => assembly);
}
_logger.LogTrace($"Assembly loaded from path: {assemblyPath}");
return assembly;
}
}
}