-
Notifications
You must be signed in to change notification settings - Fork 1
/
AssemblyLoaderExtensions.cs
92 lines (85 loc) · 3.29 KB
/
AssemblyLoaderExtensions.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
using EasyOC.AssemblyLoader;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;
using System.Reflection;
namespace EasyOC
{
public static class AssemblyLoaderExtensions
{
public static WebApplicationBuilder LoadExternalLibs(this WebApplicationBuilder builder)
{
LoadAssembliesAndTypes(builder);
builder.Services.AddSingleton<IModuleNamesProvider, ExternalModuleNamesProvider>();
return builder;
}
public static void LoadAssembliesAndTypes(WebApplicationBuilder builder)
{
var paths = builder.Configuration.GetSection("OrchardCore:ExternalLib:Paths").Get<string[]>();
if (paths is null || !paths.Any())
{
return;
}
var libsRoot = RootPathFactory(builder);
foreach (var libraryPath in paths)
{
var folder = libraryPath;
if (!Path.IsPathRooted(libraryPath))
{
folder = Path.Combine(libsRoot, libraryPath);
}
// 加载库文件
if (Directory.Exists(folder))
{
foreach (var assemblyFilePath in Directory.GetFiles(folder, "*.dll", SearchOption.AllDirectories))
{
try
{
var assembly = Assembly.LoadFrom(assemblyFilePath);
if (!ExternalModuleNamesProvider.ExternalAssemblies.Contains(assembly))
{
ExternalModuleNamesProvider.ExternalAssemblies.Add(assembly);
}
Console.WriteLine(assembly.FullName + "已加载");
}
catch (Exception ex)
{
Console.WriteLine(assemblyFilePath + "程序集加载失败");
Console.WriteLine($"{ex}");
}
}
}
}
}
static Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// 从已加载的程序集中查找依赖项
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.FullName == args.Name)
{
// 找到了相应的依赖项
return assembly;
}
}
// 未找到相应的依赖项
return null;
}
private static string RootPathFactory(WebApplicationBuilder builder)
{
var contentRootPath = builder.Environment.ContentRootPath;
var libsRoot = Path.Combine(contentRootPath, "App_Data");
var appData = Environment.GetEnvironmentVariable("ORCHARD_APP_DATA");
if (!string.IsNullOrEmpty(appData))
{
libsRoot = Path.Combine(contentRootPath, appData);
}
else
{
libsRoot = Path.Combine(contentRootPath, "App_Data");
}
return libsRoot;
}
}
}