Assembly.GetEntryAssembly()不适用于 Web 应用程序。
但是……我真的需要这样的东西。我使用一些在 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 临时文件夹中的给定代码生成程序集获取有关包含该页面/视图的项目的信息?(我认为不是,但谁知道......)