Assembly.GetEntryAssembly() не работает для веб-приложений.
Но... Мне действительно нужно что-то подобное. Я работаю с некоторым глубоко вложенным кодом, который используется как в веб-приложениях, так и в не-веб-приложениях.
Мое текущее решение - просмотреть 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 получить информацию о проекте, который содержит эту страницу/представление? (Думаю, нет, но кто знает...)