当前位置: 首页 > news >正文

Asp.net Core 反射加载dll

  1. 定义一个类库,定义接口
namespace Plugin
{public interface IPlugin{void EllisTest();}
}
  1. 定义另外一个类库,引用上面的类库,实现接口
using Plugin;namespace UserCustom
{public class Custom : IPlugin{public  void EllisTest(){Console.WriteLine("哈哈,今天这个天气挺好的");}}
}
  1. 定义API,使用assemble加载dll
[HttpGet(Name = "test")]
public IActionResult DirectLoad()
{Assembly assembly = Assembly.LoadFrom("C:\\Users\\84977\\Desktop\\UserCustom.dll");var pluginType = assembly.GetTypes().FirstOrDefault(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);if (pluginType != null){IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);plugin.EllisTest();}return Ok();
}[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{string pluginPath = "C:\\Users\\84977\\Desktop\\UserCustom.dll";var pluginLoader = new PluginLoader();pluginLoader.LoadAndExecutePlugin(pluginPath);return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateTime.Now.AddDays(index),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();
} 
  1. 使用AssemblyLoadContext 加载dll
public class CustomAssemblyLoadContext : AssemblyLoadContext{public CustomAssemblyLoadContext() : base(isCollectible: true){}protected override Assembly Load(AssemblyName assemblyName){return null; // 返回 null 以使用默认的加载机制}}public class PluginLoader{public void LoadAndExecutePlugin(string pluginPath){var context = new CustomAssemblyLoadContext();// 加载插件程序集var assembly = context.LoadFromAssemblyPath(pluginPath);// 查找实现了 IPlugin 接口的类型var pluginType = assembly.GetTypes().FirstOrDefault(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);if (pluginType != null){// 创建插件实例并调用方法var plugin = (IPlugin)Activator.CreateInstance(pluginType);plugin.EllisTest();}assembly = null;GC.Collect();GC.WaitForPendingFinalizers();context.Unload();// 在此处,当 using 块结束时,AssemblyLoadContext 会被卸载,从而实现 DLL 的热卸载。}}
http://www.lryc.cn/news/391700.html

相关文章:

  • 利用coredump获取程序调用通路
  • DVWA sql手注学习(巨详细不含sqlmap)
  • 代码随想录算法训练营第70天图论9[1]
  • 浏览器设计为默认
  • windows USB 设备驱动开发-USB设备描述符
  • 【踩坑】修复报错Cannot find DGL libdgl_sparse_pytorch_2.2.0.so
  • postman中参数和x-www-form-urlencoded传值的区别
  • 自己训练 PaddleOCR
  • 基于SpringBoot的地方废物回收机构管理系统
  • 跑腿平台小程序的设计
  • Java技术栈总结:Redis篇
  • django models对应的mysql类型
  • 2024攻防演练:亚信安全新一代WAF,关键时刻守护先锋
  • 富格林:曝光有效方案安全交易
  • ArtTS系统能力-窗口管理的学习(3.2)
  • C++ 运算符的优先级和关联性表
  • 正则表达式替换字符串的方法
  • 开源模型应用落地-FastAPI-助力模型交互-WebSocket篇(五)
  • 2024/7/4总结
  • 【Android面试八股文】Looper如何在子线程中创建?
  • IT项目管理文档体系
  • ELK企业内部日志分析系统(1)
  • 反序列化POP链技术详解
  • process.env.VUE_APP_BASE_API
  • 面试题--SpirngCloud
  • 中位数贪心,3086. 拾起 K 个 1 需要的最少行动次数
  • xml_woarchive undefined symbol
  • SiCat:一款多功能漏洞利用管理与搜索工具
  • 毕业论文初稿写作方法与过程
  • SLAM 精度评估