I need to find the assembly in which managed code execution started.
// using System.Reflection;
Assembly entryAssembly = Assembly.GetEntryAssembly();
This seems like the way to go, but the MSDN reference page for Assembly.GetEntryAssembly
states that this method "[c]an return null when called from unmanaged code."
In that case, I would like to know which assembly was called by unmanaged code.
Is there a reliable way of doing this, i.e. one that always returns a non-null Assembly
reference?
The best I could think of so far is the following, which should work in a single-threaded scenario:
(The above snippet is optimized for ease of understanding, not for execution speed or memory efficiency.)
Another (largely untested) starting point for a working solution might be something like this:
Some uncertainties remain:
Modules and assemblies are not the same thing.
ProcessModule
might even be conceptually different fromModule
. Would the above code always work in the presence of multi-module (i.e. multi-file) assemblies, especially when an assembly's entry point is not in the manifest module?Is
Process.MainModule
guaranteed to always returns a non-null reference?I tried both methods of stakx.
Method based on MainModule does not work in some special cases (dynamic assemblies for example).
Method based on StackTrace can return an assembly too high (or low) in the hierarchy, like mscorlib.
I made a little variant which works well in my use cases :
Basically, I walk the stack up until I find a conventional method named "Main" with
void
orint
return type. If no such method is found, I look for a method invoked via reflection. For example, NUnit uses that invocation to load unit tests.Of course, I do that only if
Assembly.GetEntryAssembly()
returnsnull
.