Assembly.GetEntryAssembly()不适用于网络应用程序。
但是...我真的需要这样的东西。
我使用一些在 Web 和非 Web 应用程序中使用的深度嵌套代码。
我当前的解决方案是浏览 StackTrace 以查找第一个调用的程序集。
/// <summary>
/// Version of 'GetEntryAssembly' that works with web applications
/// </summary>
/// <returns>The entry assembly, or the first called assembly in a web application</returns>
public static Assembly GetEntyAssembly()
{
// get the entry assembly
var result = Assembly.GetEntryAssembly();
// if none (ex: web application)
if (result == null)
{
// current method
MethodBase methodCurrent = null;
// number of frames to skip
int framestoSkip = 1;
// loop until we cannot got further in the stacktrace
do
{
// get the stack frame, skipping the given number of frames
StackFrame stackFrame = new StackFrame(framestoSkip);
// get the method
methodCurrent = stackFrame.GetMethod();
// if found
if ((methodCurrent != null)
// and if that method is not excluded from the stack trace
&& (methodCurrent.GetAttribute<ExcludeFromStackTraceAttribute>(false) == null))
{
// get its type
var typeCurrent = methodCurrent.DeclaringType;
// if valid
if (typeCurrent != typeof (RuntimeMethodHandle))
{
// get its assembly
var assembly = typeCurrent.Assembly;
// if valid
if (!assembly.GlobalAssemblyCache
&& !assembly.IsDynamic
&& (assembly.GetAttribute<System.CodeDom.Compiler.GeneratedCodeAttribute>() == null))
{
// then we found a valid assembly, get it as a candidate
result = assembly;
}
}
}
// increase number of frames to skip
framestoSkip++;
} // while we have a working method
while (methodCurrent != null);
}
return result;
}
为了确保组装是我们想要的,我们有3个条件:
- 该程序集不在 GAC 中
- 装配体不是动态的
- 不生成程序集(以避免临时 asp.net 文件
我遇到的最后一个问题是当基页在单独的程序集中定义时。
(我使用 ASP.Net MVC,但它与 ASP.Net 相同)。
在这种特殊情况下,返回的是单独的程序集,而不是包含页面的程序集。
我现在正在寻找的是:
1)我的装配验证条件是否足够? (我可能忘记了案例)
2) 有没有办法从 ASP.Net 临时文件夹中给定的代码生成的程序集获取有关包含该 Page / View 的项目的信息?
(我想不是,但谁知道呢......)
这似乎是获取 Web 应用程序的“入口”或主程序集的可靠且简单的方法。
如果将控制器放在单独的项目中,您可能会发现 ApplicationInstance 的基类与包含视图的 MVC 项目不在同一个程序集中 - 但是,这种设置似乎很少见(我提到它是因为我已经尝试过这个曾经设置过,不久前一些博客支持了这个想法)。
static private Assembly GetWebEntryAssembly()
{
if (System.Web.HttpContext.Current == null ||
System.Web.HttpContext.Current.ApplicationInstance == null)
{
return null;
}
var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP") {
type = type.BaseType;
}
return type == null ? null : type.Assembly;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)