Assembly.GetEntryAssembly()不适用于Web应用程序。用于Web应用程序的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文件
我遇到的最后一个问题是当基本页面被定义为单独的sembly。 (我使用ASP.Net MVC,但它将与ASP.Net一样)。 在这种特殊情况下,返回的是单独的程序集,而不是包含页面的程序集。
我正在寻找的是:
1)我的程序集验证条件是否足够? (我可能已经忘记了案例)
2)有没有一种方法,从ASP.Net临时文件夹中给定的代码生成的程序集中获取有关包含Page/View的项目的信息? (我想不会,但谁知道...)
“入口程序集”在ASP.NET应用程序中并没有任何意义,因为许多ASP.NET应用程序都是在适当的时间串联执行代码的大量程序集。你究竟在做什么? – Levi 2010-11-27 10:42:05
我完全同意你,一个Web应用程序作为“入门程序集”。实际上,我们可以认为他们有多个切入点。我最终需要的是在入口程序集中获取AssemblyInfo.cs文件中的内容。为什么我想要这样做,这不是重点。 – Mose 2010-12-01 13:00:21
我需要做一个类似的任务,并且通常找不到比这更好的方法。 ExcludeFromStackTraceAttribute是你的一类吗?我似乎无法在BCL中找到它。 `GetAttribute <>`同样的问题是,你为了方便而创建了一个方法吗? – 2011-07-19 19:38:48