c# - 使用Assembly.Load 正确加载依赖项

主程序代码

删除dll依旧可以执行

https://files.cnblogs.com/files/NanShengBlogs/sample.zip

 

 

 

 1  static void Main(string[] args)
 2         {
 3             //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
 4             string dir= Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 5 
 6             AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
 7 
 8             Assembly ass = Assembly.Load(File.ReadAllBytes(Path.Combine(dir,"ClassLibrary2.dll")));
 9 
10             List<Assembly> assDepe = new List<Assembly>();
11 
12             Type t = ass.GetType("ClassLibrary2.Class");
13 
14             var obj=Activator.CreateInstance(t);
15             
16             var refereces = ass.GetReferencedAssemblies();
17 
18             foreach (AssemblyName item in refereces)
19             {
20                 if (AppDomain.CurrentDomain.GetAssemblies().Count(c => c.FullName== item.FullName)==0)
21                 {
22                     assDepe.Add(Assembly.Load(File.ReadAllBytes(Path.Combine(dir,item.Name + ".dll"))));
23                 }
24             }
25             var ms = t.GetMethod("MyFunc").Invoke(obj, new object[] { 20, 30 });
26             Console.WriteLine(ms);
27             Console.ReadLine();
28         }
29 
30         private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
31         {
32            return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().FullName.Split(',')[0] == args.Name.Split(',')[0]);
33         }
34     }
"ClassLibrary2"项目

 

 

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using ClassLibrary1;
 8 
 9 namespace ClassLibrary2
10 {
11     public class Class
12     {
13         public double MyFunc(double a, double b)
14         {
15             return ClassLibrary1.mycls.MyAdd(a, b);
16         }
17     }
18 }

 

"ClassLibrary1"项目

 

 

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ClassLibrary1
 8 {
 9     public static class mycls
10     {
11         public static double MyAdd(double a,double b)
12         {
13             return a + 2*b;
14 
15         }
16         public static double MyMinus(double a, double b)
17         {
18             return a -b+5;
19 
20         }
21     }
22 }
posted @ 2020-10-17 21:01  南胜NanSheng  阅读(2252)  评论(0编辑  收藏  举报