netcore热插拔dll
2023-04-18 12:57:45 时间
项目中有有些场景用到反射挺多的,用到了反射就离不开dll的加载。此demo适用于通过反射dll运行项目中加载和删除,不影响项目。
ConsoleApp:
1 using AppClassLibrary; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Runtime.Loader; 7 using System.Threading; 8 9 namespace ConsoleApp 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Console.WriteLine("************非反射调用**************"); 16 ICommon common = new Say(); 17 common.Invoke(); 18 Console.WriteLine("************非反射调用**************"); 19 Console.WriteLine(); 20 Console.WriteLine("**************反射调用***************"); 21 InvokeMethod(); 22 Console.WriteLine("**************反射调用***************"); 23 Console.Read(); 24 } 25 private static void InvokeMethod() 26 { 27 bool IsGo = true; 28 while (IsGo) 29 { 30 Thread.Sleep(3000); 31 List<ICommon> common_List = new List<ICommon>(); 32 var path = Directory.GetCurrentDirectory(); 33 string[] fileInfos = Directory.GetFiles(path).Where(f => f.Contains("comm")).ToArray(); 34 var _AssemblyLoadContext = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true); 35 Dictionary<string, ICommon> fileInfoList = new Dictionary<string, ICommon>(); 36 foreach (var file in fileInfos) 37 { 38 ICommon common; 39 using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) 40 { 41 var assembly = _AssemblyLoadContext.LoadFromStream(fs); 42 Type type = assembly.GetExportedTypes().Where(t => t.GetInterfaces().Contains(typeof(ICommon))).FirstOrDefault(); 43 common = Activator.CreateInstance(type) as ICommon; 44 } 45 FileInfo fileInfo = new FileInfo(file); 46 common.Invoke(); 47 } 48 } 49 } 50 } 51 public class Say : ICommon 52 { 53 public void Invoke() 54 { 55 Console.WriteLine($"{this.GetType()} Say Method "); 56 } 57 } 58 }
接口类库:
using System; namespace AppClassLibrary { public interface ICommon { void Invoke(); } }
comm_Print.dll:
using AppClassLibrary; using System; namespace comm_Print { public class Print : ICommon { public void Invoke() { Console.WriteLine($"{this.GetType()} Print Method "); } } }
comm_Trace.dll:
using AppClassLibrary; using System; namespace comm_Trace { public class Trace : ICommon { public void Invoke() { Console.WriteLine($"{this.GetType()} Trace Method "); } } }
下面2个dll可以任意添加删除:
删除trace.dll运行结果:
相关文章
- 【技术种草】cdn+轻量服务器+hugo=让博客“云原生”一下
- CLB运维&运营最佳实践 ---访问日志大洞察
- vnc方式登陆服务器
- 轻松学排序算法:眼睛直观感受几种常用排序算法
- 十二个经典的大数据项目
- 为什么使用 CDN 内容分发网络?
- 大数据——大数据默认端口号列表
- Weld 1.1.5.Final,JSR-299 的框架
- JavaFX 2012:彻底开源
- 提升as3程序性能的十大要点
- 通过凸面几何学进行独立于边际的在线多类学习
- 利用行动影响的规律性和部分已知的模型进行离线强化学习
- ModelLight:基于模型的交通信号控制的元强化学习
- 浅谈Visual Source Safe项目分支
- 基于先验知识的递归卡尔曼滤波的代理人联合状态和输入估计
- 结合网络结构和非线性恢复来提高声誉评估的性能
- 最佳实践丨云开发CloudBase多环境管理实践
- TimeVAE:用于生成多变量时间序列的变异自动编码器
- 具有线性阈值激活的神经网络:结构和算法
- 内网渗透之横向移动 -- 从域外向域内进行密码喷洒攻击