我正试图为程序集集合绘制依赖矩阵,包括在哪里使用了哪些依赖方法。基本的DLL依赖矩阵很容易,但我发现很难得到方法映射。我一直在使用的工具是jbevain methodbaserrocks .cs.
我要解析的程序集的依赖项正在根据AppDomain.CurrentDomain.GetAssemblies()加载,但我正在获得FileNotFoundException和ReflectionTypeLoadExceptions。
- 是否有正确的方法来加载引用的程序集?
- 我试过LoadFile, LoadFrom和ReflectionOnlyLoadFrom都有相同的结果。
- 我如何获得使用引用类型的方法的类型?
- 我可以绕过reflectiontypeloadeexceptions错误的答案从这里,但这些方法是确切的那些我想映射
TestLibraryA.dll
namespace TestLibraryA
{
public class TestClassA
{
public int DoStuff(int a, int b)
{
return a + b;
}
}
}
TestLibaryB.dll
using TestLibraryA;
namespace TestLibraryB
{
public class TestClassB
{
public int DoStuffAgain()
{
TestClassA obj = new TestClassA();
int ans = obj.DoStuff(3, 5);
return ans;
}
public TestClassA DoOtherStuff()
{
TestClassA result = new TestClassA();
return result;
}
}
}
解析器代码应用
public List<string> GetMethods()
{
List<string> result = new List<string> { };
Assembly dependencyAssembly = Assembly.LoadFile("TestLibraryA.dll");
Assembly targetAssembly = Assembly.LoadFile("TestLibaryB.dll");
Type[] types = targetAssembly.GetTypes();
// ReflectionTypeLoadExceptions thrown if a dependency type is used
// NB Not demo'ed in this example
foreach(var type in types)
{
foreach(var method in type.GetMethods())
{
// With the above DoStuffAgain() method is returned but DoOtherStuff() is not
var instructions = MethodBodyReader.GetInstructions(method);
// FileNotFoundException thrown saying TestLibraryA.dll not loaded
// the line throwing the error is
// MethodBodyReader(method)
// this.body = method.GetMethodBody();
foreach (var instruction in instructions)
{
MethodInfo methodInfo = instruction.Operand as MethodInfo;
if (methodInfo != null)
{
result.Add(methodInfo.DeclaringType.FullName + "." + methodInfo.Name);
}
}
}
}
return result;
}
为了避免这个异常,您需要在加载TestLibaryB
之前添加下面的代码AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name == "TestLibaryA...")
{
return Assembly.LoadFrom("TestLibaryA's Path");
}
return null;
}