【发布时间】:2011-05-15 17:30:37
【问题描述】:
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 临时文件夹中的给定代码生成程序集获取有关包含该页面/视图的项目的信息? (我认为不是,但谁知道...)
【问题讨论】:
-
“入口程序集”在 ASP.NET 应用程序中没有任何意义,因为许多 ASP.NET 应用程序是在适当的时间串联执行代码的大量程序集。你到底想做什么?
-
我完全同意你的观点,一个没有“入口程序集”的网络应用程序。事实上,我们可以认为它们有多个入口点。我最终需要的是在入口程序集中获取 AssemblyInfo.cs 文件中的内容。我为什么要这样做不是重点。
-
我需要做一个类似的任务,通常找不到比这更好的方法。
ExcludeFromStackTraceAttribute是你的班级吗?我似乎无法在 BCL 中找到它。与GetAttribute<>相同的问题,这是您为方便起见而制作的方法吗? -
另外,IoC 在这个过程中投入了一把大扳手......
-
似乎有一个更简单的解决方案(使用 HttpContext.ApplicationInstance,根据 cmets):stackoverflow.com/questions/756031/…
标签: c# reflection assemblies code-generation stack-frame