I need an alternative to `Assembly.GetEntryAssembly()` that never returns null

stakx - no longer contributing picture stakx - no longer contributing · Jan 4, 2013 · Viewed 14.2k times · Source

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?

Answer

The best I could think of so far is the following, which should work in a single-threaded scenario:

// using System.Diagnostics;
// using System.Linq; 
Assembly entryAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;

(The above snippet is optimized for ease of understanding, not for execution speed or memory efficiency.)