2

Application_Start我有一个库模块,我们在所有 Web 应用程序中都使用它,它以 ASP.NET Webforms 应用程序的方法将所有加载的程序集(及其版本号)列出到我们的 log4net 日志文件中。

这已经完美运行了很长时间 - 直到今天,当我尝试在“应用程序预热”方法之后使用它时(Scott Guthrie 在他的博客文章中描述了在部署到 IIS 之后运行(并且ASP.NETApplication_Start运行之前) - 现在突然我收到一个错误:

System.NotSupportedException:动态程序集中不支持调用的成员。

报告已加载程序集的代码如下所示:

public static void ReportLoadedAssemblies(this ILog log) 
{
    if (log.IsInfoEnabled) 
    {
        log.Info("Loaded assemblies:");

        IEnumerable<Assembly> appAssemblies = AppDomain.CurrentDomain.GetAssemblies().OrderBy(c => c.ManifestModule.Name);

        foreach (Assembly asm in appAssemblies) 
        {
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            if (!fvi.CompanyName.Contains("Microsoft")) 
            {
                log.Info(String.Format("{0, -45} : {1, -15} {2}", fvi.FileDescription, fvi.FileVersion, asm.Location));
            }
        }
    }
}

我不是 100% 清楚哪一行会引发错误——我怀疑是这个:

IEnumerable<Assembly> appAssemblies = AppDomain.CurrentDomain.GetAssemblies().OrderBy(c => c.ManifestModule.Name);

那么这条消息到底在告诉我什么?在这种情况下,我怎样才能得到我加载的程序集?

4

1 回答 1

2

我认为错误不在

IEnumerable<Assembly> appAssemblies = AppDomain.CurrentDomain.GetAssemblies().OrderBy(c => c.ManifestModule.Name);

因为在动态生成程序集时访问Assembly.Location属性会抛出NotSupportedException.

那么这条消息到底在告诉我什么?

如果动态生成的程序集没有任何位置,则您无法访问该属性。是的,它可能会返回一个空字符串,但它与使用...创建的程序集相同,Assembly.Load()说真的,我无法理解这种选择的基本原理,但就是这样。

在这种情况下,我怎样才能得到我加载的程序集?

只需检查它:

foreach (Assembly asm in appAssemblies.Where(x => !x.IsDynamic)) 
{
    // Your code
}   

或者更简单:

var appAssemblies = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x => !x.IsDynamic)
    .OrderBy(c => c.ManifestModule.Name);
于 2016-01-15T14:08:09.727 回答