Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding type hierarchy assemblies using Mono.Cecil

I am trying to implement a method that receives a type and returns all the assemblies that contain its base types.

For example:
Class A is a base type (class A belongs to assembly c:\A.dll)
Class B inherits from A (class B belongs to assembly c:\B.dll)
Class C inherits from B (class C belongs to assembly c:\c.dll)

public IEnumerable<string> GetAssembliesFromInheritance(string assembly, 
                                                        string type)
{
    // If the method recieves type C from assembly c:\C.dll
    // it should return { "c:\A.dll", "c:\B.dll", "c:\C.dll" }
}

My main problem is that AssemblyDefinition from Mono.Cecil does not contain any property like Location.

How can an assembly location be found given an AssemblyDefinition?

like image 928
Elisha Avatar asked Jan 22 '11 17:01

Elisha


1 Answers

An assembly can be composed of multiple modules, so it doesn't really have a location per se. The assembly's main module does have a location though:

AssemblyDefinition assembly = ...;
ModuleDefinition module = assembly.MainModule;
string fileName = module.FullyQualifiedName;

So you could write something along the line of:

public IEnumerable<string> GetAssembliesFromInheritance (TypeDefinition type)
{
    while (type != null) {
        yield return type.Module.FullyQualifiedName;

        if (type.BaseType == null)
            yield break;

        type = type.BaseType.Resolve ();
    }
}

Or any other variant which pleases you more.

like image 60
Jb Evain Avatar answered Oct 04 '22 19:10

Jb Evain