Get dependent assemblies?

纵然是瞬间 提交于 2019-12-03 05:04:42

问题


Is there a way to get all assemblies that depend on a given assembly?

Pseudo:

Assembly a = GetAssembly();
var dependants = a.GetDependants();

回答1:


If you wish to find the dependent assemblies from the current application domain, you could use something like the GetDependentAssemblies function defined below:

private IEnumerable<Assembly> GetDependentAssemblies(Assembly analyzedAssembly)
{
    return AppDomain.CurrentDomain.GetAssemblies()
        .Where(a => GetNamesOfAssembliesReferencedBy(a)
                            .Contains(analyzedAssembly.FullName));
}

public IEnumerable<string> GetNamesOfAssembliesReferencedBy(Assembly assembly)
{
    return assembly.GetReferencedAssemblies()
        .Select(assemblyName => assemblyName.FullName);
}

The analyzedAssembly parameter represents the assembly for which you want to find all the dependents.




回答2:


Programatically, you can use Mono.Cecil to do this.

Something like this (note this won't work if the debugger is attached - e.g. if you run it from inside VS itself):

public static IEnumerable<string> GetDependentAssembly(string assemblyFilePath)
{
   //On my box, once I'd installed Mono, Mono.Cecil could be found at: 
   //C:\Program Files (x86)\Mono-2.10.8\lib\mono\gac\Mono.Cecil\0.9.4.0__0738eb9f132ed756\Mono.Cecil.dll
   var assembly = AssemblyDefinition.ReadAssembly(assemblyFilePath);
   return assembly.MainModule.AssemblyReferences.Select(reference => reference.FullName);
}

If you don't need to do this programatically, then NDepend or Reflector can give you this information.




回答3:


First define your scope, e.g.:

  1. All assemblies in my application's bin directory

  2. All assemblies in my application's bin directory + all assemblies in the GAC

  3. All assemblies on any machine in the world.

Then simply (*) iterate through all assemblies in your scope, and use reflection to check if they depend on your target assembly.

If you want indirect as well as direct references, you'll have to rinse and repeat for all the assemblies you find.

(*) Might not be quite so simple if your scope is 3 above.




回答4:


I'm not aware of any built-in possibility to get dependencies at runtime. So I think the easiest solution is define an extension method and use code from this application. I used an application itself a years ago. But do not use code of it.

Hope this helps.



来源:https://stackoverflow.com/questions/8849289/get-dependent-assemblies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!