private Assembly[] LoadReferencedAssemblies()
        {
            var assemblies = new List <Assembly>()
            {
                Assembly
            };

#if DEBUG
            _trace.WriteLine($"[NetCoreAssemblyRuntimeLoader][LoadReferencedAssemblies] Loading references for [{Assembly}]");
#endif
            foreach (var assemblyName in Assembly.GetReferencedAssemblies())
            {
                try
                {
#if DEBUG
                    _trace.WriteLine($"[NetCoreAssemblyRuntimeLoader][LoadReferencedAssemblies] Attempting to load [{assemblyName}]");
#endif
                    assemblies.Add(_loadContext.LoadFromAssemblyName(assemblyName));
                }
                catch (Exception ex)
                {
                    // exception occurred, but we don't care
#if DEBUG
                    _trace.Error(ex, $"[NetCoreAssemblyRuntimeLoader][LoadReferencedAssemblies] Failed to load [{assemblyName}]");
#endif
                }
            }

            return(assemblies.ToArray());
        }
            protected override Assembly?Load(AssemblyName assemblyName)
            {
                var simpleName = assemblyName.Name !;

                if (_loader.AssemblySimpleNamesToBeLoadedInCompilerContext.Contains(simpleName))
                {
                    // Delegate to the compiler's load context to load the compiler or anything
                    // referenced by the compiler
                    return(_compilerLoadContext.LoadFromAssemblyName(assemblyName));
                }

                var assemblyPath = Path.Combine(Directory, simpleName + ".dll");
                var paths        = _loader.GetPaths(simpleName);

                if (paths is null)
                {
                    // The analyzer didn't explicitly register this dependency. Most likely the
                    // assembly we're trying to load here is netstandard or a similar framework
                    // assembly. In this case, we want to load it in compiler's ALC to avoid any
                    // potential type mismatch issue. Otherwise, if this is truly an unknown assembly,
                    // we assume both compiler and default ALC will fail to load it.
                    return(_compilerLoadContext.LoadFromAssemblyName(assemblyName));
                }

                Debug.Assert(paths.Any());
                // A matching assembly in this directory was specified via /analyzer.
                if (paths.Contains(assemblyPath))
                {
                    return(LoadFromAssemblyPath(_loader.GetPathToLoad(assemblyPath)));
                }

                AssemblyName?bestCandidateName = null;
                string?      bestCandidatePath = null;

                // The assembly isn't expected to be found at 'assemblyPath',
                // but some assembly with the same simple name is known to the loader.
                foreach (var candidatePath in paths)
                {
                    // Note: we assume that the assembly really can be found at 'candidatePath'
                    // (without 'GetPathToLoad'), and that calling GetAssemblyName doesn't cause us
                    // to hold a lock on the file. This prevents unnecessary shadow copies.
                    var candidateName = AssemblyName.GetAssemblyName(candidatePath);
                    // Checking FullName ensures that version and PublicKeyToken match exactly.
                    if (candidateName.FullName.Equals(assemblyName.FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(LoadFromAssemblyPath(_loader.GetPathToLoad(candidatePath)));
                    }
                    else if (bestCandidateName is null || bestCandidateName.Version < candidateName.Version)
                    {
                        bestCandidateName = candidateName;
                        bestCandidatePath = candidatePath;
                    }
                }

                Debug.Assert(bestCandidateName != null);
                Debug.Assert(bestCandidatePath != null);

                return(LoadFromAssemblyPath(_loader.GetPathToLoad(bestCandidatePath)));
            }
        private static IReadOnlyList <MetadataReference> GetReferences(
            AssemblyLoadContext assemblyLoadContext,
            Assembly parentAssembly)
        {
            void PopulateTransitiveDependencies(Assembly assembly, ISet <AssemblyName> assemblyNames)
            {
                foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies())
                {
                    // Avoid doing the same work twice
                    if (!assemblyNames.Add(referencedAssemblyName))
                    {
                        continue;
                    }

                    var referencedAssembly = assemblyLoadContext.LoadFromAssemblyName(referencedAssemblyName);
                    PopulateTransitiveDependencies(referencedAssembly, assemblyNames);
                }
            }

            IEnumerable <MetadataReference> EnumerateReferences()
            {
                // Implicit references

                yield return(assemblyLoadContext
                             .LoadFromAssemblyName(new AssemblyName("Microsoft.CSharp"))
                             .ToMetadataReference());

                yield return(assemblyLoadContext
                             .LoadFromAssemblyName(typeof(TemplateBase <>).Assembly.GetName())
                             .ToMetadataReference());

                yield return(assemblyLoadContext
                             .LoadFromAssemblyName(parentAssembly.GetName())
                             .ToMetadataReference());

                // References from parent assembly
                var transitiveDependencies = new HashSet <AssemblyName>(AssemblyNameEqualityComparer.Instance);

                PopulateTransitiveDependencies(parentAssembly, transitiveDependencies);

                foreach (var dependency in transitiveDependencies)
                {
                    yield return(assemblyLoadContext
                                 .LoadFromAssemblyName(dependency)
                                 .ToMetadataReference());
                }
            }

            return(EnumerateReferences().Distinct().ToArray());
        }
        static Assembly LoadAssembly(String assemblyName, AssemblyLoadContext loadContext)
        {
            try
            {
                Logger.Log("Load assembly: " + assemblyName);

                String executingAseemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                //Assembly^ assembly = AssemblyLoadContext::GetLoadContext(Reflection::Assembly::GetExecutingAssembly())->LoadFromAssemblyPath(
                //	Path::Combine(executingAseemblyPath, (gcnew Reflection::AssemblyName(assemblyName))->Name + ".dll"));

                AssemblyName actualAssemblyName = new AssemblyName(assemblyName);

                Logger.Log("Actual assembly name is " + actualAssemblyName);

                Assembly assembly = loadContext.LoadFromAssemblyName(actualAssemblyName);

                //Assembly^ assembly = loadContext->LoadFromAssemblyPath(
                //	Path::Combine(executingAseemblyPath, (gcnew Reflection::AssemblyName(assemblyName))->Name + ".dll"));

                return(assembly);
            }
            catch (System.Exception ex)
            {
                Logger.Log("Unable to load assembly: " + assemblyName + " with: " + ex.ToString());
            }

            return(null);
        }
        protected override Assembly Load(AssemblyName assemblyName)
        {
            if (assemblyName.Name == null)
            {
                return(null);
            }

            try
            {
                var defaultAssembly = _defaultLoadContext.LoadFromAssemblyName(assemblyName);
                if (defaultAssembly != null)
                {
                    return(defaultAssembly);
                }
            }
            catch
            {
            }

            var resolvedPath = _dependencyResolver.ResolveAssemblyToPath(assemblyName);

            if (!string.IsNullOrEmpty(resolvedPath) && File.Exists(resolvedPath))
            {
                return(LoadFromAssemblyPath(resolvedPath));
            }

            var localFile = Path.Combine(_basePath, assemblyName.Name + ".dll");

            if (File.Exists(localFile))
            {
                return(LoadFromAssemblyPath(localFile));
            }

            return(base.Load(assemblyName));
        }
Exemple #6
0
        private static Type FindClassType(Guid clsid, string assemblyPath, string assemblyName, string typeName)
        {
            try
            {
                AssemblyLoadContext alc    = GetALC(assemblyPath);
                var      assemblyNameLocal = new AssemblyName(assemblyName);
                Assembly assem             = alc.LoadFromAssemblyName(assemblyNameLocal);
                Type     t = assem.GetType(typeName);
                if (t != null)
                {
                    return(t);
                }
            }
            catch (Exception e)
            {
                if (IsLoggingEnabled())
                {
                    Log($"COM Activation of {clsid} failed. {e}");
                }
            }

            const int CLASS_E_CLASSNOTAVAILABLE = unchecked ((int)0x80040111);

            throw new COMException(string.Empty, CLASS_E_CLASSNOTAVAILABLE);
        }
Exemple #7
0
        public void InitializeIsolation(bool isolated)
        {
            if (isolated == false)
            {
                alc             = new AssemblyLoadContext("Isolated", isCollectible: true);
                defaultAssembly = Assembly.GetExecutingAssembly();
                alcAssembly     = alc.LoadFromAssemblyPath(defaultAssembly.Location);

                Assert.AreEqual(alcAssembly, alc.LoadFromAssemblyName(alcAssembly.GetName()));

                alcProgramType = alcAssembly.GetType("ContextualReflectionTest.Program");

                AssemblyLoadContext.Default.Resolving += TestResolve.ResolvingTestDefault;
                alc.Resolving += TestResolve.ResolvingTestIsolated;

                alcProgramInstance = (IProgram)Activator.CreateInstance(alcProgramType);
            }
            else
            {
                alcAssembly        = Assembly.GetExecutingAssembly();
                alc                = AssemblyLoadContext.GetLoadContext(alcAssembly);
                alcProgramType     = typeof(Program);
                alcProgramInstance = this;
                defaultAssembly    = AssemblyLoadContext.Default.LoadFromAssemblyName(alcAssembly.GetName());
            }
        }
Exemple #8
0
        public static IInputPlugin Load(IDependencyBuilder builder, InputConfiguration configuration, AssemblyLoadContext assemblyLoader)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (string.IsNullOrWhiteSpace(configuration.InputType))
            {
                throw new Exception("Can not instantiate a translation plugin without a plugin name.");
            }

            var assemblyName = $"{typeof(InputPluginLoader).Namespace}.{configuration.InputType}";
            var assembly     = assemblyLoader.LoadFromAssemblyName(new AssemblyName(assemblyName));

            var type = assembly.GetExportedTypes().FirstOrDefault(x => typeof(IInputPlugin).GetTypeInfo().IsAssignableFrom(x));

            if (type == null)
            {
                throw new Exception($"Can not find a class implementing '{nameof(IInputPlugin)}' in assembly '{assembly.FullName}'.");
            }

            var plugin = Activator.CreateInstance(type) as IInputPlugin;

            if (plugin == null)
            {
                throw new Exception($"Couldn't instantiate '{type.Name}' plugin.");
            }

            plugin.RegisterPlugin(configuration, builder);

            return(plugin);
        }
Exemple #9
0
        private static Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
        {
            // avoid loading *.resources dlls, because of: https://github.com/dotnet/coreclr/issues/8416
            if (assemblyName.Name.EndsWith("resources"))
            {
                return(null);
            }

            // check cached assemblies first
            RuntimeLibrary library = DependencyContext.Default.RuntimeLibraries.FirstOrDefault(runtimeLibrary => runtimeLibrary.Name == assemblyName.Name);

            if (library != null)
            {
                return(context.LoadFromAssemblyName(new AssemblyName(library.Name)));
            }

            // try known directories
            string found = context.Assemblies.Select(x => Path.Combine(Path.GetDirectoryName(x.Location), $"{assemblyName.Name}.dll")).Distinct().FirstOrDefault(File.Exists);

            if (found != null)
            {
                return(context.LoadFromAssemblyPath(found));
            }

            // try gac
            found = Directory.GetFileSystemEntries(Environment.ExpandEnvironmentVariables("%windir%\\Microsoft.NET\\assembly"), $"{assemblyName.Name}.dll", SearchOption.AllDirectories).FirstOrDefault();

            return(found == null ? null : context.LoadFromAssemblyPath(found));
        }
        public void SatelliteLoadsCorrectly(string alc, string assemblyName, string culture)
        {
            AssemblyName satelliteAssemblyName = new AssemblyName(assemblyName + ".resources");
            satelliteAssemblyName.CultureInfo = new CultureInfo(culture);

            AssemblyLoadContext assemblyLoadContext = contexts[alc];

            Assembly satelliteAssembly = assemblyLoadContext.LoadFromAssemblyName(satelliteAssemblyName);

            Assert.NotNull(satelliteAssembly);

            AssemblyName parentAssemblyName = new AssemblyName(assemblyName);
            Assembly parentAssembly = assemblyLoadContext.LoadFromAssemblyName(parentAssemblyName);

            Assert.Equal(AssemblyLoadContext.GetLoadContext(parentAssembly), AssemblyLoadContext.GetLoadContext(satelliteAssembly));
        }
Exemple #11
0
        private static Assembly OnAssemblyResolve(
            AssemblyLoadContext assemblyLoadContext,
            AssemblyName assemblyName)
        {
            try
            {
                AssemblyLoadContext.Default.Resolving -= OnAssemblyResolve;
                return(assemblyLoadContext.LoadFromAssemblyName(assemblyName));
            }
            catch
            {
                // Intercept assembly load context failure
                // Check to see if it's Dapper loading a DLL from .NET framework.
                if (assemblyName.Name == MicrosoftSqlServerTypeAssembly)
                {
                    return(typeof(SqlGeography).Assembly);
                }

                throw; // New other error
            }
            finally
            {
                AssemblyLoadContext.Default.Resolving += OnAssemblyResolve;
            }
        }
Exemple #12
0
        /// <summary>
        /// The Load method override causes all the dependencies present in the plugin's binary directory to get loaded
        /// into the HostAssemblyLoadContext together with the plugin assembly itself.
        /// The Interface assembly must not be present in the plugin's binary directory, otherwise we would
        /// end up with the assembly being loaded twice. Once in the default context and once in the HostAssemblyLoadContext.
        /// </summary>
        /// <param name="assemblyName">The assembly name to load.</param>
        /// <returns></returns>
        protected override Assembly Load(AssemblyName assemblyName)
        {
            if (null == assemblyName.Name)
            {
                return(null);
            }

            try
            {
                var assembly = _defaultLoadContext.LoadFromAssemblyName(assemblyName);
                if (null != assembly)
                {
                    return(assembly);
                }
            }
            catch (Exception)
            {
                string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
                _traceService.Debug($"Resolving dependency: {assemblyName.Name}, v{assemblyName.Version} from componentAssemblyPath: {PluginPath}");

                if (assemblyPath != null)
                {
                    _traceService.Debug($"Resolved dependency. Loading {assemblyPath} into the PluginAssemblyLoadContext");
                    return(LoadFromAssemblyPath(assemblyPath));
                }
                else
                {
                    _traceService.Debug($"Failed resolving dependency: {assemblyName.Name}, v{assemblyName.Version}");
                }
            }

            return(null);
        }
Exemple #13
0
        /// <summary>
        /// Loads nng native library using specified load context and returns factory instance to create nng objects.
        /// </summary>
        /// <param name="loadContext">Load context into which native library is loaded</param>
        /// <param name="factoryName">Name of factory type instance to create</param>
        /// <returns></returns>
        public static IAPIFactory <IMessage> Init(AssemblyLoadContext loadContext, string factoryName = "nng.Factories.Compat.Factory")
        {
            var assem = loadContext.LoadFromAssemblyName(new AssemblyName(managedAssemblyName));
            var type  = assem.GetType(factoryName);

            return((IAPIFactory <IMessage>)Activator.CreateInstance(type));
        }
Exemple #14
0
        private static Assembly AssemblyLoadContext_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
        {
            _logger.Info($"Resolving: {assemblyName.FullName}");
            var assembly = context.LoadFromAssemblyName(assemblyName);

            return(assembly);
        }
        protected override Assembly?Load(AssemblyName assemblyName)
        {
            if (assemblyName.Name == null)
            {
                return(null);
            }

            if (_sharedAssemblies.Contains(assemblyName.Name))
            {
                return(_mainLoadContext.LoadFromAssemblyName(assemblyName));
            }

            string?assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);

            if (assemblyPath != null)
            {
                AssemblyLoadedPath = assemblyPath;

                // Load in memory to prevent locking the file
                using var assemblyFile = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                string pdbPath = Path.ChangeExtension(assemblyPath, ".pdb");

                if (File.Exists(pdbPath))
                {
                    using var pdbFile = File.Open(pdbPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    return(LoadFromStream(assemblyFile, pdbFile));
                }

                return(LoadFromStream(assemblyFile));
            }

            return(null);
        }
Exemple #16
0
        /// <summary>
        /// Loads nng native library using specified load context and returns factory instance to create nng objects.
        /// </summary>
        /// <param name="loadContext">Load context into which native library is loaded</param>
        /// <returns></returns>
        public static IAPIFactory <IMessage> Init(AssemblyLoadContext loadContext)
        {
            var assem = loadContext.LoadFromAssemblyName(new System.Reflection.AssemblyName(managedAssemblyName));
            var type  = assem.GetType("nng.Tests.TestFactory");

            return((IAPIFactory <IMessage>)Activator.CreateInstance(type));
        }
Exemple #17
0
        private static Type GetTypeFromContext(AssemblyLoadContext ctx)
        {
            var asm  = ctx.LoadFromAssemblyName(new AssemblyName(_assemblyName1));
            var type = asm.GetType(_typeName);

            return(type);
        }
        public BundleBuilderProxy(AssemblyLoadContext assemblyLoadContext, IReporter reporter)
        {
            if (assemblyLoadContext == null)
            {
                throw new ArgumentNullException(nameof(assemblyLoadContext));
            }

            if (reporter == null)
            {
                throw new ArgumentNullException(nameof(reporter));
            }

            _assemblyLoadContext = assemblyLoadContext;
            _reporter            = reporter;

            Assembly bundlingAssembly;

            try { bundlingAssembly = assemblyLoadContext.LoadFromAssemblyName(new AssemblyName(BundlingAssemblyName)); }
            catch (Exception ex) { throw new InvalidOperationException($"Failed to load the {BundlingAssemblyName} assembly.", ex); }

            Type bundleBuilderClass;

            if ((_bundlingConfigurationType = bundlingAssembly.GetType("Karambolo.AspNetCore.Bundling.DesignTimeBundlingConfiguration", throwOnError: false, ignoreCase: false)) == null ||
                (_configFileConfigurationType = bundlingAssembly.GetType("Karambolo.AspNetCore.Bundling.Internal.DesignTime.ConfigFileConfiguration", throwOnError: false, ignoreCase: false)) == null ||
                (bundleBuilderClass = bundlingAssembly.GetType("Karambolo.AspNetCore.Bundling.Internal.DesignTime.BundleBuilder", throwOnError: false, ignoreCase: false)) == null ||
                (_processMethodDefinition = bundleBuilderClass.GetMethod("ProcessAsync",
                                                                         BindingFlags.Static | BindingFlags.Public,
                                                                         null,
                                                                         new[] { typeof(Dictionary <string, object>), typeof(CancellationToken) },
                                                                         null)) == null)
            {
                throw new NotSupportedException($"The version of {BundlingAssemblyName} referenced by the application does not support design-time bundling. Please update the bundling library's NuGet packages and CLI tools to the latest version.");
            }
        }
        private WeakReference LoadIntoALCAndUnload(string alcName, string assemblyName)
        {
            AssemblyLoadContext ctx = new AssemblyLoadContext(nameof(LoadAppAssemblyAndUnload), isCollectible: true);
            Assembly            asm = ctx.LoadFromAssemblyName(new AssemblyName("FeatureTest"));

            ctx.Unload();
            return(new WeakReference(ctx));
        }
Exemple #20
0
        /// <summary>
        /// Loads the Market Api interop.
        /// </summary>
        /// <param name="loadContext">Load context into which native library is loaded</param>
        /// <returns></returns>
        internal static IMarketApiInterop Init(AssemblyLoadContext loadContext)
        {
            var assem    = loadContext.LoadFromAssemblyName(new System.Reflection.AssemblyName(managedAssemblyName));
            var type     = assem.GetType("GolemMarketApiMockup.GolemMarketApiInterop");
            var instance = Activator.CreateInstance(type);

            return((IMarketApiInterop)instance);
        }
            protected override IEnumerable <TypeInfo> GetExportedTypes(AssemblyName assemblyName)
            {
                var assembly          = _loadContext.LoadFromAssemblyName(assemblyName);
                var exportedTypes     = assembly.ExportedTypes;
                var exportedTypeInfos = exportedTypes.Select(type => type.GetTypeInfo());

                return(exportedTypeInfos);
            }
        private static IReadOnlyList <Assembly> LoadAssemblyFromName(
            AssemblyLoadContext loadContext,
            AssemblyName assemblyName,
            IEnumerable <string> dependencyDirectories,
            Core.ILogger logger = null)
        {
            // If assembly exists in any of the dependency paths then load it from there.
            var dependencyPath = dependencyDirectories.
                                 Select(d =>
            {
                try
                {
                    return
                    (Directory.EnumerateFiles(d, $"{assemblyName.Name}.dll", SearchOption.AllDirectories).
                     FirstOrDefault());
                }
                catch (Exception)
                {
                    return(null);
                }
            }).
                                 Where(p => p != null).
                                 FirstOrDefault();

            if (!string.IsNullOrEmpty(dependencyPath))
            {
                return(LoadAssemblyFromPath(loadContext, dependencyPath, dependencyDirectories, logger));
            }

            // Otherwise load by name from the context.
            var output = new List <Assembly>();

            try
            {
                output.Add(loadContext.LoadFromAssemblyName(assemblyName));
                logger?.LogTrace($"Loaded assembly: '{output[0].FullName}'");
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger?.LogWarning($"Failed to load assembly: {e.Message.ToDistinctLines()}");
                }
                return(Array.Empty <Assembly>());
            }

            // Load referenced assemblies.
            foreach (var referencedAssemblyName in output[0].GetReferencedAssemblies())
            {
                if (!IsAssemblyLoaded(referencedAssemblyName))
                {
                    output.AddRange(
                        LoadAssemblyFromName(loadContext, referencedAssemblyName, dependencyDirectories, logger));
                }
            }

            return(output);
        }
Exemple #23
0
        /// <summary>
        /// Creates the link between the client and the server, while also passing in all the information to the server for setup
        /// </summary>
        /// <param name="alc">The target AssemblyLoadContext</param>
        /// <param name="typeName">Name of the proxied type</param>
        /// <param name="assemblyName">path of the assembly to the type</param>
        /// <param name="genericTypes">any generics that we need the proxy to work with</param>
        /// <exception cref="ArgumentNullException">Throws if we're missing either the given ALC, the AssemblyName to load, or the type to load from the assembly</exception>
        public void SetUpServer(AssemblyLoadContext alc, string typeName, AssemblyName assemblyName, object[] constructorParams, Type[] genericTypes)
        {
            if (alc == null || typeName == null || assemblyName == null)
            {
                throw new ArgumentNullException();
            }
            if (genericTypes == null)
            {
                genericTypes = new Type[] { }
            }
            ;
            if (constructorParams == null)
            {
                constructorParams = new object[] { }
            }
            ;
            Assembly a = alc.LoadFromAssemblyName(assemblyName);

            // Find the type we're going to proxy inside the loaded assembly
            Type objType = FindTypeInAssembly(typeName, a);
            // Get the interface of the object so we can set it as the server's generic type
            Type interfaceType = FindInterfaceType(_intType.Name, objType);

            if (interfaceType.IsGenericType)
            {
                interfaceType = interfaceType.MakeGenericType(genericTypes.Select(x => ConvertType(x, alc)).ToArray());
            }
            // Load *this* (ALCProxy.Communication) assembly into the ALC so we can get the server into the ALC
            Assembly serverAssembly = alc.LoadFromAssemblyName(Assembly.GetAssembly(_serverType).GetName());
            // Get the server type, then make it generic with the interface we're using
            Type serverType = FindTypeInAssembly(_serverTypeName, serverAssembly).MakeGenericType(interfaceType);

            // Give the client its reference to the server
            SerializeParameters(constructorParams, out IList <object> serializedConstArgs, out IList <Type> argTypes);
            ConstructorInfo ci = serverType.GetConstructor(
                new Type[] { typeof(Type), typeof(Type[]), typeof(IList <object>), typeof(IList <Type>) });

            _server         = ci.Invoke(new object[] { objType, genericTypes, serializedConstArgs.ToList(), argTypes });
            _serverDelegate = (ServerCall)Delegate.CreateDelegate(typeof(ServerCall), _server, serverType.GetMethod("CallObject"));
            // Attach to the unloading event
            alc.Unloading += UnloadClient;
        }
 public static Assembly?TryLoadFromAssemblyName(this AssemblyLoadContext loadContext, AssemblyName name)
 {
     try
     {
         return(loadContext.LoadFromAssemblyName(name));
     }
     catch
     {
         return(null);
     }
 }
Exemple #25
0
        private Assembly TryGetWellKnownAssembly(AssemblyLoadContext context, AssemblyName assemblyName)
        {
            if (!_wellKnownAssemblyNames.Contains(assemblyName.Name))
            {
                return(null);
            }

            assemblyName.Version = _currentAssemblyVersion;

            return(context.LoadFromAssemblyName(assemblyName));
        }
Exemple #26
0
 private static bool TryLoadAssembly(AssemblyLoadContext context, AssemblyName name, [NotNullWhen(true)] out Assembly?assembly)
 {
     try {
         assembly = context.LoadFromAssemblyName(name);
         return(true);
     }
     catch (FileNotFoundException) {
         Console.WriteLine($"[WARN] Could not find assembly '{name.FullName}'.");
         assembly = null;
         return(false);
     }
 }
Exemple #27
0
        internal static Assembly?TryResolveAssemblyFromPaths(AssemblyLoadContext context, AssemblyName assemblyName, string searchPath, Dictionary <string, Assembly>?knownAssemblyPaths = null, ILogger?logger = null)
        {
            logger?.LogTrace($"Trying to resolve assembly {assemblyName.FullName}.");

            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 = knownAssemblyPaths?.ContainsKey(candidatePath) == true;
                    if (isAssemblyLoaded || !File.Exists(candidatePath))
                    {
                        continue;
                    }

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

                    try
                    {
                        var assembly = context.LoadFromAssemblyPath(candidatePath);

                        logger?.LogTrace($"Loaded assembly from {candidatePath}.");

                        return(assembly);
                    }
                    catch
                    {
                        if (assemblyName.Name != null)
                        {
                            // We were unable to load the assembly from the file path. It is likely that
                            // a different version of the assembly has already been loaded into the context.
                            // Be forgiving and attempt to load assembly by name without specifying a version.
                            return(context.LoadFromAssemblyName(new AssemblyName(assemblyName.Name)));
                        }
                    }
                }
            }

            return(null);
        }
 public override Assembly Load(AssemblyName assemblyName)
 {
     try
     {
         return(AssemblyContext.LoadFromAssemblyName(assemblyName));
     }
     catch (Exception e)
     {
         _logger.LogError("名称加载程序集错误,原因:{1}", e);
         return(null);
     }
 }
Exemple #29
0
        private static Assembly LoadAssembly(string assemblyName, AssemblyLoadContext ctx)
        {
            if (LoadedAssemblies.ContainsKey(assemblyName))
            {
                return(LoadedAssemblies[assemblyName]);
            }

            var assembly = ctx.LoadFromAssemblyName(new AssemblyName(PrivateAssemblies[assemblyName]));

            LoadedAssemblies.Add(assemblyName, assembly);

            return(assembly);
        }
            protected override Assembly Load(AssemblyName assemblyName)
            {
                // Try to load from well-known paths. This will be called when loading a dependency of an extension.
                var assembly = _loader.Load(assemblyName.ToString());

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

                // If we don't have an entry, then fall back to the default load context. This allows extensions
                // to resolve assemblies that are provided by the host.
                return(_parent.LoadFromAssemblyName(assemblyName));
            }