From 7a6d68b7e4bf4abae7c197a06ec20e6e0680ccbd Mon Sep 17 00:00:00 2001 From: Bogdan Zavu Date: Wed, 17 Jan 2024 14:41:18 -0500 Subject: [PATCH] try to reuse loaded dll --- src/DynamoPackages/PackageLoader.cs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/DynamoPackages/PackageLoader.cs b/src/DynamoPackages/PackageLoader.cs index f3de4dc40f3..4f96e79eaef 100644 --- a/src/DynamoPackages/PackageLoader.cs +++ b/src/DynamoPackages/PackageLoader.cs @@ -713,23 +713,39 @@ internal static AssemblyLoadingState TryMetaDataContextLoad(string filename,Meta /// /// Attempt to load a managed assembly in to LoadFrom context. /// - /// The filename of a DLL + /// The filename of a DLL /// out Assembly - the passed value does not matter and will only be set if loading succeeds /// Returns true if success, false if BadImageFormatException (i.e. not a managed assembly) - internal static bool TryLoadFrom(string filename, out Assembly assem) + internal static bool TryLoadFrom(string filePath, out Assembly assem) { try { - assem = Assembly.LoadFrom(filename); + assem = Assembly.LoadFrom(filePath); return true; } catch (FileLoadException e) { + // If the exception is having HRESULT of 0x80131621 ( a dll with the same name is already loaded ), then we will attempt to use that loaded dll. + if (e.HResult == unchecked((int)0x80131621)) + { + Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); + string fileName = Path.GetFileNameWithoutExtension(filePath); + foreach (Assembly loadedAssembly in loadedAssemblies) + { + if (loadedAssembly.FullName.StartsWith(fileName, StringComparison.OrdinalIgnoreCase)) + { + assem = loadedAssembly; + return true; + } + } + } + // If the exception is having HRESULT of 0x80131515, then we need to instruct the user to "unblock" the downloaded DLL. if (e.HResult == unchecked((int)0x80131515)) { throw new DynamoServices.AssemblyBlockedException(e.Message); } + assem = null; return false; }