According to How the Runtime Locates Assemblies step 2 is Checking for Previously Referenced Assemblies.
However, in the code below you can see that this is definitely not happening. In the first line, an assembly is loaded (which should make it a "previously referenced assembly" for all future calls.)
However, a couple lines later when the code calls AppDomain.CurrentDomain.CreateInstance, the AssemblyResolve event is fired, indicating that the runtime is unable to locate the requested assembly.
You can tell the assembly is loaded, because from the AssemblyResolve event I am returning the assembly directly from CurrentDomain.GetAssemblies() !!
So, the obvious question is, why is the runtime not finding the referenced assembly as step 2 of "How the Runtime Locates Assemblies" would imply?
In order to run this example: Create a new console app, then add a new ClassLibrary to that solution and leave it named ClassLibrary1. Paste the below code into the Console Application's class Program:
class Program
{
static void Main(string[] args)
{
Assembly asmbly = Assembly.LoadFile(Path.GetFullPath(@"..\..\..\ClassLibrary1\bin\Debug\ClassLibrary1.dll"));
Type firstType = asmbly.GetTypes().First();
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
object myInstance = AppDomain.CurrentDomain.CreateInstance(asmbly.FullName, firstType.FullName);
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//WHY AM I HERE?
return AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(p => p.FullName == args.Name);
}
}
then add using references like so:
using System.Reflection;
using System.IO;
Note that I've deliberately left the original paths here such that the runtime will not find the assembly as according to Step 4: Locating the Assembly through Codebases or Probing My scenario is such that I am trying to deliberately use the functionality defined in Step 2. If the runtime can locate the path via Step 4, that will work correctly. It is step 2 that is not working.
Thanks.