1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Reflection;
5 using System.Runtime.Loader;
6
7 namespace LoadDLL
8 {
9 /// <summary>
10 /// 程序集加载器
11 /// </summary>
12 public class AssemblyLoader
13 {
14 private string _basePath;
15 private AssemblyLoadContext context;
16
17
18 public AssemblyLoader(string basePath)
19 {
20 _basePath = basePath;
21 }
22
23 public Type Load(string dllFileName, string typeName)
24 {
25 context = new AssemblyLoadContext(dllFileName);
26 context.Resolving += Context_Resolving;
27 //需要绝对路径
28 string path = Path.Combine(_basePath, dllFileName);
29 if (File.Exists(path))
30 {
31 try
32 {
33 using (var stream = File.OpenRead(path))
34 {
35 Assembly assembly = context.LoadFromStream(stream);
36 Type type = assembly.GetType(typeName);
37 dicTypes.Add(typeName, type);
38 return type;
39 }
40 }
41 catch (Exception ex)
42 {
43 Console.WriteLine($"加载节点{dllFileName}-{typeName}发生异常:{ex.Message},{ex.StackTrace}");
44 }
45
46 }
47 else
48 {
49 Console.WriteLine($"节点动态库{dllFileName}不存在:{path}");
50 }
51 return null;
52 }
53
54 /// <summary>
55 /// 加载依赖文件
56 /// </summary>
57 /// <param name="context"></param>
58 /// <param name="assemblyName"></param>
59 /// <returns></returns>
60 private Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
61 {
62 string expectedPath = Path.Combine(_basePath, assemblyName.Name + ".dll"); ;
63 if (File.Exists(expectedPath))
64 {
65 try
66 {
67 using (var stream = File.OpenRead(expectedPath))
68 {
69 return context.LoadFromStream(stream);
70 }
71 }
72 catch (Exception ex)
73 {
74 Console.WriteLine($"加载节点{expectedPath}发生异常:{ex.Message},{ex.StackTrace}");
75 }
76 }
77 else
78 {
79 Console.WriteLine($"依赖文件不存在:{expectedPath}");
80 }
81 return null;
82 }
83 }
84 }