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