Asp.Net 加载不同项目程序集
2024-08-27 01:14:09
我们做项目时有时候不想添加别的项目的引用,但是那个项目又必须在 Global 中进行注册
最常见的就是插件机制,参考: https://shazwazza.com/post/Developing-a-plugin-framework-in-ASPNET-with-medium-trust.aspx
我们知道如果不添加引用在主程序中是无法使用其程序集的
我们可以自己加载其程序集
推荐做法是将dll文件先copy到 AppDomain.CurrentDomain.DynamicDirectory 中
然后在 AppDomain.CurrentDomain.DynamicDirectory 中进行 Assembly.Load
下面的代码没有进行copy了
1、命名空间顶部的程序开始时加载程序集必须添加,其中的2个参数分别时当前类及要执行的方法
2、使用Assembly.Load对程序集进行加载
[assembly: PreApplicationStartMethod(typeof(PatulouManager), "Initialize")]
namespace IdeaSite.Web.Framework
{
public class PatulouManager
{
private const string PatulousPath = "~/Patulous"; public static void Initialize()
{
var patulouFolder = new DirectoryInfo(MapPath(PatulousPath));
var patulouFiles = patulouFolder.GetFiles("*.dll", SearchOption.AllDirectories);
foreach (var patulouFile in patulouFiles.Where(x => !IsAlreadyLoaded(x)))
{
var shadowCopiedAssembly = Assembly.Load(AssemblyName.GetAssemblyName(patulouFile.FullName));
BuildManager.AddReferencedAssembly(shadowCopiedAssembly);
}
} /// <summary>
/// 获取物理路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string MapPath(string path)
{
if (HostingEnvironment.IsHosted)
{
//hosted
return HostingEnvironment.MapPath(path);
} //not hosted. For example, run in unit tests
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
return Path.Combine(baseDirectory, path);
} /// <summary>
/// 是否已加入程序集
/// </summary>
/// <param name="fileInfo"></param>
/// <returns></returns>
private static bool IsAlreadyLoaded(FileInfo fileInfo)
{
try
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileInfo.FullName);
if (fileNameWithoutExt == null)
throw new Exception(string.Format("Cannot get file extension for {0}", fileInfo.Name));
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
string assemblyName = a.FullName.Split(new[] { ',' }).FirstOrDefault();
if (fileNameWithoutExt.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
}
catch (Exception exc)
{
Debug.WriteLine("Cannot validate whether an assembly is already loaded. " + exc);
}
return false;
}
}
}
最新文章
- 【Asphyre引擎】今天终于把精灵demo基本改好了。
- 分析递归式 Solving Recurrences------GeeksforGeeks 翻译
- Jenkins master在windows上安装
- form提交的时候使用method=get导致乱码
- C#面向对象——方法的重载及构造函数、静态对象。
- iOS开发内购图文教程
- (转)HTML表格边框的设置小技巧
- do while 与while的区别!
- WPF - 为什么不能往Library的工程中添加WPF window
- 【knockoutjs】 Computed VS Pure Computed 区别
- 匿名委托与Lambda表达式
- BAT面试技巧
- Git submodule - 子模块【转】
- U66785 行列式求值
- prime算法
- SCOI2016幸运数字(树剖/倍增/点分治+线性基)
- Python的双向链表实现
- python,pycharm安装
- 人脸识别ArcfaceDemo for Windows 分享
- 多路复用 阻塞/非阻塞IO模型 网络IO两个阶段
热门文章
- 人脸替换(FaceSwap)的一些思考
- Linux下java进程CPU占用率高分析方法(一)
- Hystrix原理与实战(转)
- ffmpeg x264安装
- flutter 中文件工具类
- ISO/IEC 9899:2011 条款6.5.8——关系操作符
- Python3基础 函数 参数为list 使用+=会影响到外部的实参
- java IO 文件批量重命名
- ES6深入浅出-3 三个点运算 &; 新版字符串-1.函数与对象的语法糖
- Bmp格式图片与16进制的互相转换简解 Python