GetEntryAssembly для веб-приложений

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? (Думаю, что нет, но кто знает ...)

45
задан Mose 1 December 2010 в 13:03
поделиться