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一時フォルダー内の特定のコード生成アセンブリから、そのページ/ビューを含むプロジェクトに関する情報を取得する方法はありますか?(私はそうは思いませんが、誰が知っていますか...)