如何循环当前加载的程序集?

时间:2008-12-20 20:15:09

标签: .net assemblies

我的ASP.NET应用程序中有一个“诊断”页面,用于验证数据库连接,显示当前的appSettings和ConnectionStrings等。此页面的一部分显示重要的程序集版本整个过程中使用的类型,但我无法弄清楚如何有效地显示所有已加载程序集的版本。

在.NET应用程序中找出所有当前引用和/或加载的程序集的最有效方法是什么?

注意:我对基于文件的方法不感兴趣,比如在特定目录中迭代* .dll。我对应用程序实际上正在使用的内容感兴趣。

2 个答案:

答案 0 :(得分:188)

获取当前AppDomain的加载程序集:

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

获取另一个程序集引用的程序集:

var referencedAssemblies = someAssembly.GetReferencedAssemblies();

请注意,如果程序集A引用了程序集B并且加载了程序集A,那么这并不意味着也会加载程序集B.只有在需要时才会加载程序集B.出于这个原因,GetReferencedAssemblies()返回AssemblyName个实例而不是Assembly个实例。

答案 1 :(得分:21)

此扩展方法以递归方式获取所有引用的程序集,包括嵌套程序集。

当它使用ReflectionOnlyLoad时,它会将程序集加载到一个单独的AppDomain中,这样做的好处就是不会干扰JIT进程。

您会注意到还有MyGetMissingAssembliesRecursive。您可以使用它来检测引用的任何缺少的程序集,但由于某种原因不在当前目录中。使用MEF时,这非常有用。返回列表将为您提供缺少的程序集以及谁拥有它(其父项)。

/// <summary>
///     Intent: Get referenced assemblies, either recursively or flat. Not thread safe, if running in a multi
///     threaded environment must use locks.
/// </summary>
public static class GetReferencedAssemblies
{
    static void Demo()
    {
        var referencedAssemblies = Assembly.GetEntryAssembly().MyGetReferencedAssembliesRecursive();
        var missingAssemblies = Assembly.GetEntryAssembly().MyGetMissingAssembliesRecursive();
        // Can use this within a class.
        //var referencedAssemblies = this.MyGetReferencedAssembliesRecursive();
    }

    public class MissingAssembly
    {
        public MissingAssembly(string missingAssemblyName, string missingAssemblyNameParent)
        {
            MissingAssemblyName = missingAssemblyName;
            MissingAssemblyNameParent = missingAssemblyNameParent;
        }

        public string MissingAssemblyName { get; set; }
        public string MissingAssemblyNameParent { get; set; }
    }

    private static Dictionary<string, Assembly> _dependentAssemblyList;
    private static List<MissingAssembly> _missingAssemblyList;

    /// <summary>
    ///     Intent: Get assemblies referenced by entry assembly. Not recursive.
    /// </summary>
    public static List<string> MyGetReferencedAssembliesFlat(this Type type)
    {
        var results = type.Assembly.GetReferencedAssemblies();
        return results.Select(o => o.FullName).OrderBy(o => o).ToList();
    }

    /// <summary>
    ///     Intent: Get assemblies currently dependent on entry assembly. Recursive.
    /// </summary>
    public static Dictionary<string, Assembly> MyGetReferencedAssembliesRecursive(this Assembly assembly)
    {
        _dependentAssemblyList = new Dictionary<string, Assembly>();
        _missingAssemblyList = new List<MissingAssembly>();

        InternalGetDependentAssembliesRecursive(assembly);

        // Only include assemblies that we wrote ourselves (ignore ones from GAC).
        var keysToRemove = _dependentAssemblyList.Values.Where(
            o => o.GlobalAssemblyCache == true).ToList();

        foreach (var k in keysToRemove)
        {
            _dependentAssemblyList.Remove(k.FullName.MyToName());
        }

        return _dependentAssemblyList;
    }

    /// <summary>
    ///     Intent: Get missing assemblies.
    /// </summary>
    public static List<MissingAssembly> MyGetMissingAssembliesRecursive(this Assembly assembly)
    {
        _dependentAssemblyList = new Dictionary<string, Assembly>();
        _missingAssemblyList = new List<MissingAssembly>();
        InternalGetDependentAssembliesRecursive(assembly);

        return _missingAssemblyList;
    }

    /// <summary>
    ///     Intent: Internal recursive class to get all dependent assemblies, and all dependent assemblies of
    ///     dependent assemblies, etc.
    /// </summary>
    private static void InternalGetDependentAssembliesRecursive(Assembly assembly)
    {
        // Load assemblies with newest versions first. Omitting the ordering results in false positives on
        // _missingAssemblyList.
        var referencedAssemblies = assembly.GetReferencedAssemblies()
            .OrderByDescending(o => o.Version);

        foreach (var r in referencedAssemblies)
        {
            if (String.IsNullOrEmpty(assembly.FullName))
            {
                continue;
            }

            if (_dependentAssemblyList.ContainsKey(r.FullName.MyToName()) == false)
            {
                try
                {
                    var a = Assembly.ReflectionOnlyLoad(r.FullName);
                    _dependentAssemblyList[a.FullName.MyToName()] = a;
                    InternalGetDependentAssembliesRecursive(a);
                }
                catch (Exception ex)
                {
                    _missingAssemblyList.Add(new MissingAssembly(r.FullName.Split(',')[0], assembly.FullName.MyToName()));
                }
            }
        }
    }

    private static string MyToName(this string fullName)
    {
        return fullName.Split(',')[0];
    }
}

更新

要使此代码线程安全,请在其周围放置lock。它默认情况下目前不是线程安全的,因为它引用了一个共享的静态全局变量来实现其魔力。