diff --git a/src/XMakeTasks/CodeTaskFactory.cs b/src/XMakeTasks/CodeTaskFactory.cs index 6fb9a56841e..7303f598029 100644 --- a/src/XMakeTasks/CodeTaskFactory.cs +++ b/src/XMakeTasks/CodeTaskFactory.cs @@ -30,6 +30,37 @@ namespace Microsoft.Build.Tasks /// public class CodeTaskFactory : ITaskFactory { + /// + /// This dictionary keeps track of custom references to compiled assemblies. The in-memory assembly is loaded from a byte + /// stream and as such its dependencies cannot be found unless they are in the MSBuild.exe directory or the GAC. They + /// cannot be found even if they are already loaded in the AppDomain. This dictionary knows the FullName of the assembly + /// and a reference to the assembly itself. In the handler, the dictionary + /// is used to return the loaded assemblies as a way to allow custom references that are not in the normal assembly Load + /// context. + /// + private static readonly IDictionary s_knownReferenceAssemblies = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + static CodeTaskFactory() + { + // The handler is not detached because it only returns assemblies for custom references that cannot be found in the normal Load context + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve; + } + + /// + /// Handles the event to return assemblies loaded from custom references. + /// + /// + /// + /// + private static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) + { + Assembly assembly = null; + // Return the assembly loaded from the custom reference if the FullName matches what is being looked for + s_knownReferenceAssemblies.TryGetValue(args.Name, out assembly); + + return assembly; + } + /// /// Default assemblies names to reference during inline code compilation - from the .NET Framework /// @@ -657,6 +688,7 @@ private void AddReferenceAssemblyToReferenceList(List referenceAssemblyL if (candidateAssembly != null) { candidateAssemblyLocation = candidateAssembly.Location; + s_knownReferenceAssemblies[candidateAssembly.FullName] = candidateAssembly; } } catch (BadImageFormatException e)