Pergunta

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

Pseudo:

Assembly a = GetAssembly();
var dependants = a.GetDependants();
Foi útil?

Solução

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.

Outras dicas

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.

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top