当前位置: 首页> 娱乐> 影视 > Asp.net Core 反射加载dll

Asp.net Core 反射加载dll

时间:2025/7/13 17:53:31来源:https://blog.csdn.net/weixin_43632687/article/details/140127011 浏览次数:0次
  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 的热卸载。}}
关键字:Asp.net Core 反射加载dll

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: