C# Getting Parent Assembly Name of Calling Assembly

六月ゝ 毕业季﹏ 提交于 2019-11-29 16:00:46

问题


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.

So the calls go like this:

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

return NULL

Does anybody know if there is a way to get to the assembly name of the First Assembly?

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);
}
}
}

and Test project method

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.");
        }
}
}

回答1:


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();

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.

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();

Edit - as of Sep. 23rd, 2015

Please, notice that

GetMethod().ReflectedType

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.




回答2:


This will return the the initial Assembly that references your currentAssembly.

var currentAssembly = Assembly.GetExecutingAssembly();
var callerAssemblies = new StackTrace().GetFrames()
            .Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
            .Where(x => x.GetReferencedAssemblies().Any(y => y.FullName == currentAssembly.FullName));
var initialAssembly = callerAssemblies.Last();



回答3:


Assembly.GetEntryAssembly() is null if you run tests from nunit-console too.

If you just want the name of the executing app then use:

 System.Diagnostics.Process.GetCurrentProcess().ProcessName 

or

 Environment.GetCommandLineArgs()[0];

For nunit-console you would get "nunit-console" and "C:\Program Files\NUnit 2.5.10\bin\net-2.0\nunit-console.exe" respectively.




回答4:


It worked for me using this:

System.Reflection.Assembly.GetEntryAssembly().GetName()



回答5:


Try:

Assembly.GetEntryAssembly().ManifestModule.Name

This should be the assembly that was actually executed to start your process.




回答6:


Not completely sure what you're looking for, especially as when running in the context of a unit test you'll wind up with:

mscorlib.dll
Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll

(or something similar depending on your test runner) in the set of assemblies that lead to any method being called.

The below code prints the names of each of the assemblies involved in the call.

var trace = new StackTrace();
var assemblies = new List<Assembly>();
var frames = trace.GetFrames();

if(frames == null)
{
    throw new Exception("Couldn't get the stack trace");
}

foreach(var frame in frames)
{
    var method = frame.GetMethod();
    var declaringType = method.DeclaringType;

    if(declaringType == null)
    {
        continue;
    }

    var assembly = declaringType.Assembly;
    var lastAssembly = assemblies.LastOrDefault();

    if(assembly != lastAssembly)
    {
        assemblies.Add(assembly);
    }
}

foreach(var assembly in assemblies)
{
    Debug.WriteLine(assembly.ManifestModule.Name);
}



回答7:


If you know the number of frame in the stack, you can use the StackFrame object and skip the number of previous frame.

// You skip 2 frames
System.Diagnostics.StackFrame stack = new System.Diagnostics.StackFrame(2, false);
string assemblyName = stack.GetMethod().DeclaringType.AssemblyQualifiedName;

But, if you want the first call, you need to get all frames and take the first. (see AVee solution)




回答8:


How about Assembly.GetEntryAssembly()? It returns the main executable of the process.

Process.GetCurrentProcess().MainModule.ModuleName should also return about the same as the ManifestModule name ("yourapp.exe").




回答9:


This works for getting the original assembly when using two assemblies in an NUnit test, without returning a NULL. Hope this helps.

var currentAssembly = Assembly.GetExecutingAssembly();
var callerAssemblies = new StackTrace().GetFrames()
        .Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
        .Where(x => x.GetReferencedAssemblies().Any(y => y.FullName ==     currentAssembly.FullName));
var initialAssembly = callerAssemblies.Last();


来源:https://stackoverflow.com/questions/11014280/c-sharp-getting-parent-assembly-name-of-calling-assembly

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