示例#1
0
        private static ConcurrentDictionary <string, AdditionalAssemblyServerSide> DiscoverAdditionalAssemblies()
        {
            var results = new ConcurrentDictionary <string, AdditionalAssemblyServerSide>(StringComparer.OrdinalIgnoreCase);

            foreach (var path in Directory.GetFiles(AppContext.BaseDirectory, "*.dll"))
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info($"Attempting to load additional assembly from '{path}'.");
                }

                try
                {
                    var name      = AssemblyLoadContext.GetAssemblyName(path);
                    var assembly  = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                    var reference = CreateMetadataReferenceFromAssembly(assembly);

                    results.TryAdd(name.Name, new AdditionalAssemblyServerSide(name, assembly, reference, AdditionalAssemblyType.BaseDirectory));

                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info($"Loaded additional assembly from '{path}' and registered it under '{name.Name}'.");
                    }
                }
                catch (Exception e)
                {
                    if (Logger.IsOperationsEnabled)
                    {
                        Logger.Operations($"Could not load additional assembly from '{path}'.", e);
                    }
                }
            }

            return(results);
        }
        public async Task Load_Works()
        {
            var testContext = await SetupLoadedPluginTextContext();

            var loadContext                = testContext.Sut();
            var assemblyLoadStrategy       = testContext.GetMock <IAssemblyLoadStrategy>();
            var initialPluginLoadDirectory = testContext.InitialPluginLoadDirectory;
            var pluginLoadContext          = testContext.PluginLoadContext;
            var pluginDependencyContext    = testContext.GetMock <IPluginDependencyContext>();
            var newtonsoftAssemblyPath     = Path.Combine(GetPathToAssemblies(), "Newtonsoft.Json.dll");
            var newtonsoftAssembly         = Assembly.LoadFile(newtonsoftAssemblyPath);
            var newtonsoftAssemblyName     = AssemblyLoadContext.GetAssemblyName(newtonsoftAssemblyPath);

            assemblyLoadStrategy.Setup(a => a.LoadAssembly(initialPluginLoadDirectory, newtonsoftAssemblyName, pluginDependencyContext.Object,
                                                           It.IsAny <Func <string, AssemblyName, ValueOrProceed <AssemblyFromStrategy> > >(),
                                                           It.IsAny <Func <string, AssemblyName, ValueOrProceed <AssemblyFromStrategy> > >(),
                                                           It.IsAny <Func <string, AssemblyName, ValueOrProceed <RuntimeAssemblyShim> > >()))
            .Returns(new AssemblyFromStrategy
            {
                Assembly      = newtonsoftAssembly,
                CanBeReleased = true
            });

            var result = InvokeProtectedMethodOnLoadContextAndGetResult <Assembly>(
                loadContext,
                "Load",
                new object[] { newtonsoftAssemblyName });

            Assert.IsNotNull(result);
        }
示例#3
0
        private Assembly TryResolveAssemblyFromPaths(AssemblyLoadContext context, AssemblyName assemblyName, IEnumerable <string> searchPaths)
        {
            foreach (var cultureSubfolder in string.IsNullOrEmpty(assemblyName.CultureName)
                     // If no culture is specified, attempt to load directly from
                     // the known dependency paths.
                ? new[] { string.Empty }
                     // Search for satellite assemblies in culture subdirectories
                     // of the assembly search directories, but fall back to the
                     // bare search directory if that fails.
                : new[] { assemblyName.CultureName, string.Empty })
            {
                foreach (var searchPath in searchPaths)
                {
                    var candidatePath = Path.Combine(searchPath,
                                                     cultureSubfolder,
                                                     $"{assemblyName.Name}.dll");

                    if (IsAssemblyAlreadyLoaded(candidatePath) ||
                        !FileSystems.Default.FileExists(candidatePath))
                    {
                        continue;
                    }

                    AssemblyName candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath);
                    if (candidateAssemblyName.Version >= assemblyName.Version)
                    {
                        return(LoadAndCache(context, candidatePath));
                    }
                }
            }

            return(null);
        }
示例#4
0
        /// <summary>
        /// 在当前运行目录下,查找所有dll
        /// </summary>
        /// <returns></returns>
        public List <Assembly> GetAssembliesFromFolder()
        {
            var assemblies = new List <Assembly>();

#if CORE
            var files = Directory.GetFiles($"{AppContext.BaseDirectory}", "*.dll");
#else
            var files = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}", "*.dll");
#endif
            foreach (var file in files)
            {
                try
                {
#if CORE
                    assemblies.Add(Assembly.Load(AssemblyLoadContext.GetAssemblyName(file)));
#else
                    assemblies.Add(Assembly.LoadFrom(file));
#endif
                }
                catch (Exception)
                {
                    // ignored 失败的原因是非托管程序
                }
            }

            return(assemblies);
        }
示例#5
0
    public POCOParser(string assemblyPath, string classFullName)
    {
        var asmName = AssemblyLoadContext.GetAssemblyName(assemblyPath);
        var asm     = Assembly.LoadFrom(assemblyPath);

        _type = asm.GetType(classFullName);
    }
示例#6
0
        private static ContainerConfiguration WithAssembliesInPath(ContainerConfiguration configuration,
                                                                   string path, AttributedModelProvider conventions,
                                                                   SearchOption searchOption = SearchOption.TopDirectoryOnly)
        {
            var assemblies     = new List <Assembly>();
            var assemblieFiles = Directory.GetFiles(path, "*.dll", searchOption);

            foreach (var assemblyFile in assemblieFiles)
            {
                try
                {
                    var ctx = new MarvinAssemblyLoadContext();
                    AssemblyLoadContext.InitializeDefaultContext(ctx);

                    var name = AssemblyLoadContext.GetAssemblyName(assemblyFile);
                    var asm  = Assembly.Load(name);

                    assemblies.Add(asm);
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("Error loading module: " + e.Message + " from: " + path);
                }
            }

            return(configuration.WithAssemblies(assemblies, conventions));
        }
        public static void GetAssemblyNameTest_ValidAssembly()
        {
            var expectedName  = typeof(ISet <>).GetTypeInfo().Assembly.GetName();
            var actualAsmName = AssemblyLoadContext.GetAssemblyName("System.Runtime.dll");

            Assert.Equal(expectedName.FullName, actualAsmName.FullName);
        }
示例#8
0
        /// <summary>
        /// Load the assembly found at the given path in the reflection context and return assembly metadata
        /// </summary>
        /// <param name="assemblyPath">The full path to the assembly file.</param>
        /// <returns>Assembly metadata if the assembly is loaded successfully, or null if there are load errors.</returns>
        public AssemblyMetadata GetReflectedAssemblyFromFile(string assemblyPath)
        {
            if (string.IsNullOrWhiteSpace(assemblyPath))
            {
                throw new ArgumentException("assemblyPath");
            }

            AssemblyMetadata result = null;

            try
            {
#if !NETSTANDARD
                return(new AssemblyMetadata(Assembly.ReflectionOnlyLoadFrom(assemblyPath)));
#else
                return(new AssemblyMetadata(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath)));
            }
            catch (System.IO.FileLoadException ex) when(ex != null && string.Equals(ex.Message, "Assembly with same name is already loaded"))
            {
                var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyPath);
                var assembly     = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == assemblyName?.Name).FirstOrDefault();

                if (assembly != null)
                {
                    result = new AssemblyMetadata(assembly);
                }
#endif
            }
            catch
            {
            }

            return(result);
        }
        private bool TryGetAssemblyName(string path, out AssemblyName assemblyName)
        {
            assemblyName = null;
            if (!File.Exists(path))
            {
                // Path might be bin\placeholder\** if assembly came from a project-to-project reference. Since those
                // assemblies are found in the current output directory, just ignore non-existent paths. If this path
                // came from somewhere else and assembly is used, loading will fail soon enough.
                return(false);
            }

            // From http://msdn.microsoft.com/en-us/library/ms173100.aspx and AssemblyHelper.IsAssemblyManaged().
            try
            {
                assemblyName = AssemblyLoadContext.GetAssemblyName(path);
                return(true);
            }
            catch (FileNotFoundException)
            {
                // The file cannot be found (should be redundant).
            }
            catch (BadImageFormatException)
            {
                // The file is not an assembly.
            }
            catch (FileLoadException)
            {
                // The assembly has already been loaded.
            }

            return(false);
        }
示例#10
0
        private static Assembly TryResolveAssemblyFromPaths_NoLock(AssemblyLoadContext context, AssemblyName assemblyName, string searchPath)
        {
            foreach (var cultureSubfolder in string.IsNullOrEmpty(assemblyName.CultureName)
                     // If no culture is specified, attempt to load directly from
                     // the known dependency paths.
                ? new[] { string.Empty }
                     // Search for satellite assemblies in culture subdirectories
                     // of the assembly search directories, but fall back to the
                     // bare search directory if that fails.
                : new[] { assemblyName.CultureName, string.Empty })
            {
                foreach (var extension in s_extensions)
                {
                    var candidatePath = Path.Combine(
                        searchPath, cultureSubfolder, $"{assemblyName.Name}.{extension}");

                    var isAssemblyLoaded = s_pathsToAssemblies.ContainsKey(candidatePath);
                    if (isAssemblyLoaded || !File.Exists(candidatePath))
                    {
                        continue;
                    }

                    var candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath);
                    if (candidateAssemblyName.Version < assemblyName.Version)
                    {
                        continue;
                    }

                    return(LoadAndCache_NoLock(context, candidatePath));
                }
            }

            return(null);
        }
示例#11
0
 protected virtual AssemblyInfo ResolveAssembly(AssemblyName name, FileSystemInfo[] files)
 {
     if (files.Any())
     {
         var libraries = DependencyContext.Default.RuntimeLibraries;
         foreach (var file in files)
         {
             var assemblyName = AssemblyLoadContext.GetAssemblyName(file.FullName);
             if (!libraries.Any(l => this.IsCandidateLibrary(l, name)))
             {
                 try
                 {
                     var info = this.LoadAssembly(file.FullName, assemblyName);
                     if (info != null)
                     {
                         return(info);
                     }
                 }
                 catch
                 {
                     // Consume exception. Assembly failing to load should not fail all assemblies.
                 }
             }
         }
     }
     return(null);
 }
示例#12
0
        private string GetInProcDataCollectionRunsettingsFile(bool disableAppDomain)
        {
            var runSettings = Path.Combine(Path.GetTempPath(), "test_" + Guid.NewGuid() + ".runsettings");
            var inprocasm   = this.testEnvironment.GetTestAsset("SimpleDataCollector.dll");

#if !NET451
            var assemblyName = AssemblyLoadContext.GetAssemblyName(inprocasm);
#else
            var assemblyName = AssemblyName.GetAssemblyName(inprocasm);
#endif
            var fileContents = @"<RunSettings>
                                    <InProcDataCollectionRunSettings>
                                        <InProcDataCollectors>
                                            <InProcDataCollector friendlyName='Test Impact' uri='InProcDataCollector://Microsoft/TestImpact/1.0' assemblyQualifiedName='SimpleDataCollector.SimpleDataCollector, {0}'  codebase='{1}'>
                                                <Configuration>
                                                    <Port>4312</Port>
                                                </Configuration>
                                            </InProcDataCollector>
                                        </InProcDataCollectors>
                                    </InProcDataCollectionRunSettings>
                                    <RunConfiguration>
                                       <DisableAppDomain>" + disableAppDomain + @"</DisableAppDomain>
                                    </RunConfiguration>
                                </RunSettings>";

            fileContents = string.Format(fileContents, assemblyName, inprocasm);
            File.WriteAllText(runSettings, fileContents);

            return(runSettings);
        }
        // Find the assembly under 'gacRoot' and select the latest version.
        private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath)
        {
            bool assemblyFound = false;

            assemblyPath = null;

            char   dirSeparator        = IO.Path.DirectorySeparatorChar;
            string tempAssemblyDirPath = $"{gacRoot}{dirSeparator}{assemblyName.Name}";

            if (Directory.Exists(tempAssemblyDirPath))
            {
                //Enumerate all directories, sort by name and select the last. This selects the latest version.
                var chosenVersionDirectory = Directory.GetDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault();

                if (!String.IsNullOrEmpty(chosenVersionDirectory))
                {
                    //Select first or default as the directory will contain only one assembly. If nothing then default is null;
                    var foundAssemblyPath = Directory.GetFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault();

                    if (!String.IsNullOrEmpty(foundAssemblyPath))
                    {
                        AssemblyName asmNameFound = AssemblyLoadContext.GetAssemblyName(foundAssemblyPath);
                        if (IsAssemblyMatching(assemblyName, asmNameFound))
                        {
                            assemblyPath  = foundAssemblyPath;
                            assemblyFound = true;
                        }
                    }
                }
            }

            return(assemblyFound);
        }
示例#14
0
        private string GetInProcDataCollectionRunsettingsFile()
        {
            var runSettings = Path.Combine(Path.GetDirectoryName(testEnvironment.GetTestAsset(DataCollectorTests.InProDataCollectorTestProject)), "runsettingstest.runsettings");
            var inprocasm   = testEnvironment.GetTestAsset("SimpleDataCollector.dll");

#if !NET46
            var assemblyName = AssemblyLoadContext.GetAssemblyName(inprocasm);
#else
            var assemblyName = AssemblyName.GetAssemblyName(inprocasm);
#endif
            var fileContents = @"<RunSettings>
                                    <InProcDataCollectionRunSettings>
                                        <InProcDataCollectors>
                                            <InProcDataCollector friendlyName='Test Impact' uri='InProcDataCollector://Microsoft/TestImpact/1.0' assemblyQualifiedName='SimpleDataCollector.SimpleDataCollector, {0}'  codebase='{1}'>
                                                <Configuration>
                                                    <Port>4312</Port>
                                                </Configuration>
                                            </InProcDataCollector>
                                        </InProcDataCollectors>
                                    </InProcDataCollectionRunSettings>
                                </RunSettings>";

            fileContents = string.Format(fileContents, assemblyName, inprocasm);
            File.WriteAllText(runSettings, fileContents);

            return(runSettings);
        }
示例#15
0
        IEnumerable <Assembly> TryLoadAssemblies([NotNull] IEnumerable <string> filenames)
        {
            AssemblyLoadContext.Default.Resolving += AssemblyResolver.OnResolving;

            foreach (string assemblyFile in filenames.Where(File.Exists))
            {
                Assembly assembly;

                try
                {
                    var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyFile);
                    if (IsInRuntimeLibraries(assemblyName))
                    {
                        assembly = Assembly.Load(assemblyName);
                    }
                    else
                    {
                        assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile);
                    }
                }
                catch (BadImageFormatException)
                {
                    // fail on native images...
                    continue;
                }
                catch (FileLoadException ex)
                {
                    this._logger.Value.Warning(ex, "Failure Loading Assembly File {AssemblyFile}", assemblyFile);
                    continue;
                }

                yield return(assembly);
            }
        }
示例#16
0
        /// <summary>
        /// Loads the assembly from the specified path.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{T}"/> of assemblies.
        /// </returns>
        private static IEnumerable <Assembly> LoadAssembly(string path)
        {
            Assembly result;

            try
            {
#if NETSTANDARD1_5
                result = PluginResolver.DefaultPluginAssemblies.FirstOrDefault(a => a.Location.Equals(path)) ?? PluginResolver.DefaultAssemblyLoadContext.LoadFromAssemblyPath(path);
#elif NET45
                result = DefaultPluginAssemblies.FirstOrDefault(a => a.Location.Equals(path)) ?? Assembly.LoadFrom(path);
#endif
            }
            catch
            {
#if NETSTANDARD1_5
                // DefaultAssemblyLoadContext.LoadFromAssemblyPath will throw when the assembly is already
                // loaded. In that case, we can load it by its AssemblyName.
                var name = AssemblyLoadContext.GetAssemblyName(path);

                try
                {
                    result = Assembly.Load(name);
                }
                catch
                {
                    yield break;
                }
#elif NET45
                yield break;
#endif
            }

            yield return(result);
        }
示例#17
0
        // Compute the size of MSIL files in a directory, in MegaBytes
        // Top level only, excludes crossgen files.
        private double GetMSILSize(string dir)
        {
            string[] files    = Directory.GetFiles(dir);
            long     msilSize = 0;

            foreach (string file in files)
            {
                if (file.EndsWith(".ni.dll") || file.EndsWith(".ni.exe"))
                {
                    continue;
                }
                try
                {
                    AssemblyLoadContext.GetAssemblyName(file);
                }
                catch (BadImageFormatException)
                {
                    continue;
                }

                msilSize += new FileInfo(file).Length;
            }

            return(msilSize / MB);
        }
示例#18
0
        /// <summary>
        /// Facade for AssemblyName.GetAssemblyName(string)
        /// </summary>
        internal static AssemblyName GetAssemblyName(string assemblyPath)
        {
#if CORECLR // AssemblyName.GetAssemblyName(assemblyPath) is not in CoreCLR
            return(AssemblyLoadContext.GetAssemblyName(assemblyPath));
#else
            return(AssemblyName.GetAssemblyName(assemblyPath));
#endif
        }
示例#19
0
        internal static NuGetVersion GetAssemblyVersion(string path)
        {
#if NET451
            return(new NuGetVersion(AssemblyName.GetAssemblyName(path).Version));
#else
            return(new NuGetVersion(AssemblyLoadContext.GetAssemblyName(path).Version));
#endif
        }
示例#20
0
        /// <summary>
        /// Gets the assembly name at a given location.
        /// </summary>
        /// <param name="assemblyPath"></param>
        /// <returns></returns>
        public static AssemblyName GetAssemblyName(string assemblyPath)
        {
#if !NET451
            return(AssemblyLoadContext.GetAssemblyName(assemblyPath));
#else
            return(AssemblyName.GetAssemblyName(assemblyPath));
#endif
        }
示例#21
0
        private Assembly Default_Resolving(AssemblyLoadContext aContext, AssemblyName aName)
        {
            foreach (var xRef in References)
            {
                var xName = AssemblyLoadContext.GetAssemblyName(xRef);
                if (xName.Name == aName.Name)
                {
                    return(aContext.LoadFromAssemblyPath(xRef));
                }
            }

            foreach (var xRef in References)
            {
                var xKernelAssemblyDir = Path.GetDirectoryName(xRef);
                var xAssemblyPath      = Path.Combine(xKernelAssemblyDir, aName.Name);
                if (File.Exists(xAssemblyPath + ".dll"))
                {
                    return(aContext.LoadFromAssemblyPath(xAssemblyPath + ".dll"));
                }
                if (File.Exists(xAssemblyPath + ".exe"))
                {
                    return(aContext.LoadFromAssemblyPath(xAssemblyPath + ".exe"));
                }
            }

            //var xRequestingAssembly = Assembly.GetEntryAssembly();
            //if (xRequestingAssembly != null) {
            //    // check for path in as requested dll is stored, this makes referenced dll project working
            //    var xPathAsRequested = Path.Combine(Path.GetDirectoryName(xRequestingAssembly.Location), aName.Name + ".dll");
            //    if (File.Exists(xPathAsRequested)) {
            //        return aContext.LoadFromAssemblyPath(xPathAsRequested);
            //    }
            //}

            // check for assembly in working directory
            var xPathToCheck = Path.Combine(Directory.GetCurrentDirectory(), aName.Name + ".dll");

            if (File.Exists(xPathToCheck))
            {
                return(aContext.LoadFromAssemblyPath(xPathToCheck));
            }

            foreach (var xDir in AssemblySearchDirs)
            {
                var xPath = Path.Combine(xDir, aName.Name + ".dll");
                if (File.Exists(xPath))
                {
                    return(aContext.LoadFromAssemblyPath(xPath));
                }
                xPath = Path.Combine(xDir, aName.Name + ".exe");
                if (File.Exists(xPath))
                {
                    return(aContext.LoadFromAssemblyPath(xPath));
                }
            }

            return(null);
        }
示例#22
0
        public static AssemblyName GetAssemblyName(string absoluteFilePath)
        {
            if (!System.IO.File.Exists(absoluteFilePath))
            {
                return(null);
            }

            return(AssemblyLoadContext.GetAssemblyName(absoluteFilePath));
        }
示例#23
0
        private static void LoadITextResourceAssemblies()
        {
#if !NETSTANDARD1_6
            var           loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).ToList();
            List <string> loadedPaths      = new List <string>();
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    var path = a.Location;
                    loadedPaths.Add(path);
                }
                catch
                {
                    // to skip exceptions for dynamically loaded assemblies without location
                    // such as anonymously hosted dynamicmethods assembly for example
                }
            }

            var referencedPaths = Directory.GetFiles(FileUtil.GetBaseDirectory(), "*.dll");
            var toLoad          = referencedPaths.Where(referencePath => !loadedPaths.Any(loadedPath => loadedPath.Equals(referencePath, StringComparison.OrdinalIgnoreCase))).ToList();
            foreach (String path in toLoad)
            {
                try {
                    AssemblyName name = AssemblyName.GetAssemblyName(path);
                    if (iTextResourceAssemblyNames.Contains(name.Name) && !loadedAssemblies.Any(assembly => assembly.GetName().Name.Equals(name.Name)))
                    {
                        loadedAssemblies.Add(AppDomain.CurrentDomain.Load(name));
                    }
                }
                catch
                {
                }
            }
#else
            string runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            List <AssemblyName> loadedAssemblies = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).ToList();

            var referencedPaths = Directory.GetFiles(FileUtil.GetBaseDirectory(), "*.dll");
            foreach (String path in referencedPaths)
            {
                try
                {
                    AssemblyName name = AssemblyLoadContext.GetAssemblyName(path);
                    if (iTextResourceAssemblyNames.Contains(name.Name) && !loadedAssemblies.Any(assembly => assembly.Name.Equals(name.Name)))
                    {
                        Assembly newAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                        loadedAssemblies.Add(newAssembly.GetName());
                    }
                }
                catch
                {
                }
            }
#endif
        }
示例#24
0
        /// <remarks>
        /// Assumes we have a lock on _guard.
        /// </remarks>
        private static Assembly LoadAndCache(AssemblyLoadContext context, string fullPath)
        {
            var assembly = context.LoadFromAssemblyPath(fullPath);
            var name     = AssemblyLoadContext.GetAssemblyName(fullPath).FullName;

            s_pathsToAssemblies[fullPath] = assembly;
            s_namesToAssemblies[name]     = assembly;

            return(assembly);
        }
示例#25
0
        private static void LoadPlugins()
        {
            _pluginDirectory = ArkeCallFlowService.GetConfigValue("appSettings:PluginDirectory");
            var assemblies =
                from file in new DirectoryInfo(_pluginDirectory).GetFiles()
                where file.Extension.ToLowerInvariant() == ".dll"
                select Assembly.Load(AssemblyLoadContext.GetAssemblyName(file.FullName));

            ObjectContainer.GetInstance().GetSimpleInjectorContainer().RegisterPackages(assemblies);
        }
示例#26
0
        private static void LoadPlugins()
        {
            _pluginDirectory = ArkeCallFlowService.GetConfigValue("appSettings:PluginDirectory");
            var assemblies =
                from file in new DirectoryInfo(_pluginDirectory).GetFiles()
                where string.Equals(file.Extension, ".dll", StringComparison.InvariantCultureIgnoreCase)
                select Assembly.Load(AssemblyLoadContext.GetAssemblyName(file.FullName));

            ObjectContainer.GetInstance().GetSimpleInjectorContainer().RegisterPackages(assemblies);
        }
        public static void LoadFromAssemblyName_ValidTrustedPlatformAssembly()
        {
            var asmName     = AssemblyLoadContext.GetAssemblyName("System.Runtime.dll");
            var loadContext = new CustomTPALoadContext();

            // Usage of TPA and AssemblyLoadContext is mutually exclusive, you cannot use both.
            // Since the premise is that you either want to use the default binding mechanism (via coreclr TPA binder)
            // or supply your own (via AssemblyLoadContext) for your own assemblies.
            Assert.Throws(typeof(FileLoadException),
                          () => loadContext.LoadFromAssemblyName(asmName));
        }
示例#28
0
        protected override Assembly?Load(AssemblyName assemblyName)
        {
            if (WellKnownAssemblyNames.Contains(assemblyName.Name !))
            {
                // Force MSBuild assemblies to be loaded in the default ALC
                // and unify to the current version.
                return(null);
            }

            foreach (var cultureSubfolder in string.IsNullOrEmpty(assemblyName.CultureName)
                     // If no culture is specified, attempt to load directly from
                     // the known dependency paths.
                ? new[] { string.Empty }
                     // Search for satellite assemblies in culture subdirectories
                     // of the assembly search directories, but fall back to the
                     // bare search directory if that fails.
                : new[] { assemblyName.CultureName, string.Empty })
            {
                foreach (var extension in Extensions)
                {
                    var candidatePath = Path.Combine(_directory,
                                                     cultureSubfolder,
                                                     $"{assemblyName.Name}.{extension}");

                    if (!FileSystems.Default.FileExists(candidatePath))
                    {
                        continue;
                    }

                    AssemblyName candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath);
                    if (candidateAssemblyName.Version != assemblyName.Version)
                    {
                        continue;
                    }

                    return(LoadFromAssemblyPath(candidatePath));
                }
            }

            // If the Assembly is provided via a file path, the following rules are used to load the assembly:
            // - the assembly from the user specified path is loaded, if it exists, into the custom ALC, or
            // - if the simple name of the assembly exists in the same folder as msbuild.exe, then that assembly gets loaded
            //   into the default ALC (so it's shared with other uses).

            var assemblyNameInExecutableDirectory = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory,
                                                                 assemblyName.Name);

            if (FileSystems.Default.FileExists(assemblyNameInExecutableDirectory))
            {
                return(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyNameInExecutableDirectory));
            }

            return(null);
        }
示例#29
0
        /// <summary>
        /// The populate cache for type and method symbols.
        /// </summary>
        /// <param name="binaryPath">
        /// The binary path.
        /// </param>
        private void PopulateCacheForTypeAndMethodSymbols(string binaryPath)
        {
            try
            {
                var pdbFilePath = Path.ChangeExtension(binaryPath, ".pdb");
                using (var pdbReader = new PortablePdbReader(new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read)))
                {
                    // At this point, the assembly should be already loaded into the load context. We query for a reference to
                    // find the types and cache the symbol information. Let the loader follow default lookup order instead of
                    // forcing load from a specific path.
#if NET46
                    var asm = Assembly.Load(AssemblyName.GetAssemblyName(binaryPath));
#else
                    var asm = Assembly.Load(AssemblyLoadContext.GetAssemblyName(binaryPath));
#endif

                    foreach (var type in asm.GetTypes())
                    {
                        // Get declared method infos
                        var methodInfoList        = ((TypeInfo)type.GetTypeInfo()).DeclaredMethods;
                        var methodsNavigationData = new Dictionary <string, DiaNavigationData>();

                        foreach (var methodInfo in methodInfoList)
                        {
                            var diaNavigationData = pdbReader.GetDiaNavigationData(methodInfo);
                            if (diaNavigationData != null)
                            {
                                methodsNavigationData[methodInfo.Name] = diaNavigationData;
                            }
                            else
                            {
                                EqtTrace.Error(
                                    string.Format(
                                        "Unable to find source information for method: {0} type: {1}",
                                        methodInfo.Name,
                                        type.FullName));
                            }
                        }

                        if (methodsNavigationData.Count != 0)
                        {
                            this.methodsNavigationDataForType[type.FullName] = methodsNavigationData;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EqtTrace.Error("PortableSymbolReader: Failed to load symbols for binary: {0}", binaryPath);
                EqtTrace.Error(ex);
                this.Dispose();
                throw;
            }
        }
示例#30
0
        /// <summary>
        /// 从文件夹中获取所有的程序集
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="searchOption"></param>
        public static List <Assembly> GetAllAssembliesInFolder(string folderPath, SearchOption searchOption)
        {
            var assemblyFiles = Directory
                                .EnumerateFiles(folderPath, "*.*", searchOption)
                                .Where(s => s.EndsWith(".dll") || s.EndsWith(".exe"));

#if CORE
            return(assemblyFiles.Select(o => Assembly.Load(AssemblyLoadContext.GetAssemblyName(o))).ToList());
#else
            return(assemblyFiles.Select(Assembly.LoadFile).ToList());
#endif
        }