Exemplo n.º 1
0
        public IAssembly TryLoad(string dll, string pdb, string version = null)
        {
            if (string.IsNullOrWhiteSpace(dll))
            {
                throw new ArgumentException(nameof(dll));
            }
            if (string.IsNullOrWhiteSpace(pdb))
            {
                throw new ArgumentException(nameof(pdb));
            }

            // Find version if it wasn't provided
            if (string.IsNullOrWhiteSpace(version))
            {
                var assemblyName = _AssemblyNameReader.GetAssemblyName(dll);
                if (assemblyName != null)
                {
                    version = assemblyName.Version.ToString();
                }
            }

            // Used cached assembly if it is already loaded and cached
            IAssembly assembly = _AssemblyCache.FindAlreadyLoadedAssembly(dll, version);

            if (assembly != null)
            {
                return(assembly);
            }

            // Load the assembly
            assembly = _AppDomain.TryLoad(dll, pdb);
            if (assembly == null)
            {
                return(null);
            }

            var assemblyVersion = assembly.GetName()?.Version?.ToString();

            // Cache the loaded assembly (even if it is the wrong version)
            // Also, for threadsafety, get the cached assembly back, in case two threads loaded at the same time
            assembly = _AssemblyCache.Add(dll, assemblyVersion, assembly);

            // Make sure the version matches the requested version
            if (assemblyVersion != version)
            {
                return(null);
            }

            // If configured to do so, load all dependent assemblies immediately,
            if (_Settings.LoadDependenciesProactively)
            {
                var dir = Path.GetDirectoryName(dll);
                if (!dir.EndsWith("bin"))
                {
                    ProactivelyLoadDependencies(Path.Combine(dir, "bin"));
                }
            }

            return(assembly);
        }