C#获取父程序集的调用程序集的名称
我有一个正在使用的C#单元测试应用程序。涉及三个程序集-C#应用程序本身的程序集,该应用程序使用的第二个程序集以及第二个程序集使用的第三个程序集。
I've got a C# unit test application that I'm working on. There are three assemblies involved - the assembly of the C# app itself, a second assembly that the app uses, and a third assembly that's used by the second one.
因此呼叫是这样的:
First Assembly ------> Second Assembly---------> Third Assembly.
我需要在第三次集会中得到拳头大会的名称
What I need to do in the third assembly is get the name of the Fist Assembly that called the second assembly.
Assembly.GetExecutingAssembly().ManifestModule.Name
Assembly.GetCallingAssembly().ManifestModule.Name
返回第二个程序集的名称。
和
returns the name of the Second assembly. and
Assembly.GetEntryAssembly().ManifestModule.Name
返回NULL
有人知道是否有一种方法可以获取该程序集的程序集名称第一次集会?
Does anybody know if there is a way to get to the assembly name of the First Assembly?
根据其他用户的要求,我在此处放置了代码。这不是100%的代码,而是类似下面的代码。
As per the other users demand here I put the code. This is not 100% code but follow of code like this.
namespace FirstAssembly{
public static xcass A
{
public static Stream OpenResource(string name)
{
return Reader.OpenResource(Assembly.GetCallingAssembly(), ".Resources." + name);
}
}
}
using FirstAssembly;
namespace SecondAssembly{
public static class B
{
public static Stream FileNameFromType(string Name)
{
return = A.OpenResource(string name);
}
}
}
并测试项目方法
using SecondAssembly;
namespace ThirdAssembly{
public class TestC
{
[TestMethod()]
public void StremSizTest()
{
// ARRANGE
var Stream = B.FileNameFromType("ValidMetaData.xml");
// ASSERT
Assert.IsNotNull(Stream , "The Stream object should not be null.");
}
}
}
我想您应该可以这样做:
I guess you should be able to do it like this:
using System.Diagnostics;
using System.Linq;
...
StackFrame[] frames = new StackTrace().GetFrames();
string initialAssembly = (from f in frames
select f.GetMethod().ReflectedType.AssemblyQualifiedName
).Distinct().Last();
这将为您提供汇编,其中包含在当前线程中首先启动的第一个方法。因此,如果您不在主线程中,则可能与EntryAssembly有所不同,如果我正确理解您的情况,则应该是您所寻找的Assembly。
This will get you the Assembly which contains the first method which was started first started in the current thread. So if you're not in the main thread this can be different from the EntryAssembly, if I understand your situation correctly this should be the Assembly your looking for.
您可以也可以得到实际的Assembly而不是这样的名称:
You can also get the actual Assembly instead of the name like this:
Assembly initialAssembly = (from f in frames
select f.GetMethod().ReflectedType.Assembly
).Distinct().Last();
编辑-截至2015年9月23日
Edit - as of Sep. 23rd, 2015
请注意
GetMethod().ReflectedType
可以为null,因此检索其AssemblyQualifiedName可能会引发异常。
例如,如果要检查仅用于ORM(例如linq2db等)POCO类的香草c.tor,那会很有趣。
can be null, so retrieving its AssemblyQualifiedName could throw an exception. For example, that's interesting if one wants to check a vanilla c.tor dedicated only to an ORM (like linq2db, etc...) POCO class.