private static Assembly GetRuntimeAssembly(string name)
        {
            var path = Assembly.GetEntryAssembly().Location;
            var library = DependencyContext.Default.RuntimeLibraries.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault();
            if (library == null)
            {
                return null;
            }
            var r = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
        {
            new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)),
            new ReferenceAssemblyPathResolver(),
            new PackageCompilationAssemblyResolver()
        });

            var wrapper = new CompilationLibrary(
                library.Type,
                library.Name,
                library.Version,
                library.Hash,
                library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
                library.Dependencies,
                library.Serviceable);

            var assemblies = new List<string>();
            r.TryResolveAssemblyPaths(wrapper, assemblies);
            if (assemblies.Count > 0)
            {
                return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblies[0]);
            }
            else
            {
                return null;
            }
        }
Beispiel #2
0
        public void PopulatedAssemblies()
        {
            var fail    = new Mock <ICompilationAssemblyResolver>();
            var success = new Mock <ICompilationAssemblyResolver>();

            success.Setup(r => r.TryResolveAssemblyPaths(It.IsAny <CompilationLibrary>(), It.IsAny <List <string> >()))
            .Returns(true)
            .Callback((CompilationLibrary l, List <string> a) =>
            {
                a.Add("Assembly");
            });

            var resolvers = new[]
            {
                fail.Object,
                success.Object
            };

            var assemblies = new List <string>();
            var library    = TestLibraryFactory.Create();

            var resolver = new CompositeCompilationAssemblyResolver(resolvers);
            var result   = resolver.TryResolveAssemblyPaths(library, assemblies);

            assemblies.Should().Contain("Assembly");
        }
        private Assembly LoadAssembly(string path)
        {
            if (this.assembliesByPath.ContainsKey(path))
            {
                return(this.assembliesByPath[path]);
            }

            var loadContext = AssemblyLoadContext.GetLoadContext(this.GetType().GetTypeInfo().Assembly);
            var assembly    = loadContext.LoadFromAssemblyPath(path);

            var newDependencyContext = DependencyContext.Load(assembly);

            if (newDependencyContext != null)
            {
                this.dependencyContext = this.dependencyContext.Merge(newDependencyContext);
            }
            var basePath = Path.GetDirectoryName(path);

            if (!this.directoriesWithResolver.Contains(basePath))
            {
                this.assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
                {
                    new AppBaseCompilationAssemblyResolver(basePath),
                    this.assemblyResolver,
                });
                this.directoriesWithResolver.Add(basePath);
            }

            this.assembliesByPath.Add(path, assembly);
            return(assembly);
        }
Beispiel #4
0
        public void ReturnsFirstSuccessfulResolve()
        {
            var fail    = new Mock <ICompilationAssemblyResolver>();
            var success = new Mock <ICompilationAssemblyResolver>();

            success.Setup(r => r.TryResolveAssemblyPaths(It.IsAny <CompilationLibrary>(), It.IsAny <List <string> >()))
            .Returns(true);

            var failTwo = new Mock <ICompilationAssemblyResolver>();

            var resolvers = new[]
            {
                fail.Object,
                success.Object,
                failTwo.Object
            };

            var resolver = new CompositeCompilationAssemblyResolver(resolvers);
            var result   = resolver.TryResolveAssemblyPaths(null, null);

            Assert.True(result);

            fail.Verify(r => r.TryResolveAssemblyPaths(It.IsAny <CompilationLibrary>(), It.IsAny <List <string> >()),
                        Times.Once());
            success.Verify(r => r.TryResolveAssemblyPaths(It.IsAny <CompilationLibrary>(), It.IsAny <List <string> >()),
                           Times.Once());
            failTwo.Verify(r => r.TryResolveAssemblyPaths(It.IsAny <CompilationLibrary>(), It.IsAny <List <string> >()),
                           Times.Never());
        }
Beispiel #5
0
        public void PassesLibraryToAllResolvers()
        {
            var fail      = new Mock <ICompilationAssemblyResolver>();
            var failTwo   = new Mock <ICompilationAssemblyResolver>();
            var resolvers = new[]
            {
                fail.Object,
                failTwo.Object
            };

            var library = new CompilationLibrary(
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty,
                Enumerable.Empty <string>(),
                Enumerable.Empty <Dependency>(),
                false);

            var resolver = new CompositeCompilationAssemblyResolver(resolvers);
            var result   = resolver.TryResolveAssemblyPaths(library, null);

            fail.Verify(r => r.TryResolveAssemblyPaths(library, null), Times.Once());
            failTwo.Verify(r => r.TryResolveAssemblyPaths(library, null), Times.Once());
        }
        private static T GetInstanceContextPackageAssemblyNong <T>(Type clientType, string authorizationHeader, IConfigProvider configProvider,
                                                                   ClientConfiguration.ClientAdapter clientadapter = ClientConfiguration.ClientAdapter.Proxy) where T : class
        {
            try
            {
                var appDirecotry = PlatformServices.Default.Application.ApplicationBasePath;
                var appName      = PlatformServices.Default.Application.ApplicationName + ".dll";
                var direcotry    = appDirecotry + appName;
                var info2        = DependencyContext.Default.RuntimeLibraries.FirstOrDefault(x => x.Name.Contains("CotorraNube.CotoRRA.Standard.ProxyClient"));
                var Assembly     = AssemblyLoadContext.Default.LoadFromAssemblyPath(direcotry);

                var assemblyResolver = new CompositeCompilationAssemblyResolver
                                           (new ICompilationAssemblyResolver[]
                {
                    new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(direcotry)),
                    new ReferenceAssemblyPathResolver(),
                    new PackageCompilationAssemblyResolver()
                });

                var loadContext = AssemblyLoadContext.GetLoadContext(Assembly);

                if (info2 != null)
                {
                    var wrapper = new CompilationLibrary(
                        info2.Type,
                        info2.Name,
                        info2.Version,
                        info2.Hash,
                        info2.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
                        info2.Dependencies,
                        info2.Serviceable);

                    var assemblies = new List <string>();
                    assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies);
                    if (assemblies.Count > 0)
                    {
                        var  res  = loadContext.LoadFromAssemblyPath(assemblies[0]);
                        Type type = res.GetType(clientType.FullName + clientadapter.ToString());
                        if (configProvider != null)
                        {
                            return(Activator.CreateInstance(type, authorizationHeader, configProvider) as T);
                        }
                        else
                        {
                            return(Activator.CreateInstance(type, authorizationHeader) as T);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Client adapter not found", ex);
            }

            return(null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompilationGenerator"/> class
        /// with default dependency resolution and loading.
        /// </summary>
        public CompilationGenerator()
        {
            this.assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
            {
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver(),
            });
            this.dependencyContext = DependencyContext.Default;

            var loadContext = AssemblyLoadContext.GetLoadContext(this.GetType().GetTypeInfo().Assembly);

            loadContext.Resolving += this.ResolveAssembly;
        }
Beispiel #8
0
        private static IEnumerable <string> TryLoadDeps(string source)
        {
            source = Path.GetFullPath(source);
            var deps = Path.ChangeExtension(source, ".deps.json");

            if (!File.Exists(deps))
            {
                log.Trace($"Assembly {source} does not have a deps file");
                return(Enumerable.Empty <string>());
            }

            DependencyContext context;

            using (var stream = File.OpenRead(deps))
            {
                context = new DependencyContextJsonReader().Read(stream);
            }

            if (context == null)
            {
                return(Enumerable.Empty <string>());
            }

            var resolver = new CompositeCompilationAssemblyResolver
                               (new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(source)),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver()
            });

            var assemblies = new List <string>();

            foreach (var lib in context.RuntimeLibraries)
            {
                var cl = new CompilationLibrary(lib.Type, lib.Name, lib.Version, lib.Hash,
                                                lib.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths), lib.Dependencies, lib.Serviceable, lib.Path, lib.HashPath);

                resolver.TryResolveAssemblyPaths(cl, assemblies);
            }

            var index = assemblies.FindIndex(v => source.Equals(v, StringComparison.OrdinalIgnoreCase));

            if (index > -1)
            {
                assemblies.RemoveAt(index);
            }

            return(assemblies);
        }
        public Assembly LoadLibrary(string library)
        {
            Assembly assembly;

            if (library.EndsWith(".dll"))
            {
                assembly = LoadFromAssemblyPath(library);
            }
            else
            {
                assembly = LoadFromAssemblyName(new AssemblyName(library));
            }

            DependencyContext?dependencyContext = DependencyContext.Load(assembly);
            var resolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(library)),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver(),
            });

            Assembly?_OnResolving(AssemblyLoadContext context, AssemblyName name)
            {
                if (dependencyContext == null)
                {
                    return(null);
                }

                RuntimeLibrary library = dependencyContext.RuntimeLibraries.FirstOrDefault(rl => rl.Name.Equals(name.Name, StringComparison.OrdinalIgnoreCase));

                if (library != null)
                {
                    var wrapper = new CompilationLibrary(library.Type, library.Name, library.Version, library.Hash,
                                                         library.RuntimeAssemblyGroups.SelectMany(rag => rag.AssetPaths), library.Dependencies, library.Serviceable);

                    var assemblies = new List <string>();
                    resolver.TryResolveAssemblyPaths(wrapper, assemblies);
                    if (assemblies.Count > 0)
                    {
                        return(LoadFromAssemblyPath(assemblies[0]));
                    }
                }

                return(null);
            }

            Resolving += _OnResolving;

            return(assembly);
        }
Beispiel #10
0
        private void AssemblyDependencyResolver(string path)
        {
            //AssemblyLoadContext.Default.LoadFromAssemblyName(assembly);
            var assembly          = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
            var dependencyContext = DependencyContext.Load(assembly);

            var assemblyResolver = new CompositeCompilationAssemblyResolver
                                       (new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver()
            });
            var loadContext = AssemblyLoadContext.GetLoadContext(assembly);

            dependencyContext?.RuntimeLibraries.ToList().ForEach(x =>
            {
                var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
                var loadedPaths      = loadedAssemblies.Select(a => a.Location).ToArray();

                foreach (var compilationLibrary in dependencyContext.CompileLibraries.Where(y => y.Name.StartsWith("Jimu")))
                {
                    if (!loadedPaths.Select(z => Path.GetFileNameWithoutExtension(z)).ToList().Contains(compilationLibrary.Name, StringComparer.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine($"dynamic load {compilationLibrary.Name}");

                        RuntimeLibrary library = dependencyContext.RuntimeLibraries.FirstOrDefault(runtime => runtime.Name == compilationLibrary.Name);
                        var wrapper            = new CompilationLibrary(
                            library.Type,
                            library.Name,
                            library.Version,
                            library.Hash,
                            library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
                            library.Dependencies,
                            library.Serviceable);
                        var assemblies = new List <string>();
                        assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies);
                        if (assemblies.Count > 0)
                        {
                            loadContext.LoadFromAssemblyPath(assemblies[0]);
                        }
                    }
                    //DependencyDLL[library.Name] = cb;
                }
            });
        }
Beispiel #11
0
        private static IEnumerable <string> GetKnownDependencies(string addinPath)
        {
            var retval = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            var deps   = Path.ChangeExtension(addinPath, ".deps.json");

            DependencyContext context;

            using (var stream = File.OpenRead(deps))
            {
                context = new DependencyContextJsonReader().Read(stream);
            }

            if (context == null)
            {
                return(Enumerable.Empty <string>());
            }

            var resolver = new CompositeCompilationAssemblyResolver
                               (new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(addinPath)),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver()
            });

            var rid  = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.GetRuntimeIdentifier();
            var rids = new[] { rid };

            var fallbacks = context.RuntimeGraph.FirstOrDefault(f => f.Runtime == rid);

            if (fallbacks != null)
            {
                rids = rids.Concat(fallbacks.Fallbacks).ToArray();
            }

            var assemblies = new List <string>();

            foreach (var rlib in context.RuntimeLibraries)
            {
                var ridAssets = SelectAssets(rids, rlib.RuntimeAssemblyGroups);
                var cl        = new CompilationLibrary(rlib.Type, rlib.Name, rlib.Version, rlib.Hash, ridAssets, rlib.Dependencies, rlib.Serviceable, rlib.Path, rlib.HashPath);
                resolver.TryResolveAssemblyPaths(cl, assemblies);
            }

            return(assemblies.Select(Path.GetFullPath));
        }
Beispiel #12
0
        public void PassesLibraryToAllResolvers()
        {
            var fail      = new Mock <ICompilationAssemblyResolver>();
            var failTwo   = new Mock <ICompilationAssemblyResolver>();
            var resolvers = new[]
            {
                fail.Object,
                failTwo.Object
            };

            var library = TestLibraryFactory.Create();

            var resolver = new CompositeCompilationAssemblyResolver(resolvers);
            var result   = resolver.TryResolveAssemblyPaths(library, null);

            fail.Verify(r => r.TryResolveAssemblyPaths(library, null), Times.Once());
            failTwo.Verify(r => r.TryResolveAssemblyPaths(library, null), Times.Once());
        }
Beispiel #13
0
        private static void SetupInterceptorsDependencyResolver(string assemblyFolder, Assembly interceptorsAssembly)
        {
            if (Directory.GetFiles(assemblyFolder, "*.deps.json").Length > 0)
            {
                // this method loads assemblies from both assembly folder and nuget cache and requires deps.json file
                // see https://github.com/dotnet/runtime/issues/18527#issuecomment-611499261
                var dependencyContext = DependencyContext.Load(interceptorsAssembly);
                var resolver          = new ICompilationAssemblyResolver[]
                {
                    new AppBaseCompilationAssemblyResolver(assemblyFolder),
                    new ReferenceAssemblyPathResolver(),
                    new PackageCompilationAssemblyResolver()
                };
                var assemblyResolver = new CompositeCompilationAssemblyResolver(resolver);
                var loadContext      = AssemblyLoadContext.GetLoadContext(interceptorsAssembly);

                loadContext !.Resolving += (AssemblyLoadContext context, AssemblyName name) =>
                {
                    bool NamesMatch(RuntimeLibrary runtime)
                    {
                        var res = string.Equals(runtime.Name, name.Name, StringComparison.OrdinalIgnoreCase);

                        if (!res)
                        {
                            foreach (var group in runtime.RuntimeAssemblyGroups)
                            {
                                foreach (var l in group.RuntimeFiles)
                                {
                                    if (Path.GetFileNameWithoutExtension(l.Path) == name.Name)
                                    {
                                        return(true);
                                    }
                                }
                            }
                        }

                        return(res);
                    }

                    var library = dependencyContext.RuntimeLibraries.FirstOrDefault(NamesMatch);
                    if (library == null)
                    {
                        return(null);
                    }

                    var wrapper = new CompilationLibrary(
                        library.Type,
                        library.Name,
                        library.Version,
                        library.Hash,
                        library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
                        library.Dependencies,
                        library.Serviceable);

                    var assemblies = new List <string>();
                    assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies);
                    var assembly = assemblies.FirstOrDefault(a => Path.GetFileNameWithoutExtension(a) == name.Name);

                    Console.WriteLine($"Load from: {assembly}");
                    return(assembly == null ? null : Assembly.LoadFile(assembly));
                };
            }
            else
            {
                // alternative approach supports loading from assembly folder without deps.json file
                AssemblyLoadContext.Default.Resolving += (context, name) =>
                {
                    // TODO: verbose logging
                    Console.WriteLine($"AssemblyResolve: {name}");

                    // as we know only assembly name, not file name (written in deps.json) - we try to guess it
                    var probePath1 = Path.Combine(assemblyFolder, name.Name + ".dll");
                    var probePath2 = Path.Combine(assemblyFolder, name.Name + ".exe");

                    if (File.Exists(probePath1))
                    {
                        Console.WriteLine($"Found at: {probePath1}");
                        return(Assembly.LoadFile(probePath1));
                    }

                    if (File.Exists(probePath2))
                    {
                        Console.WriteLine($"Found at: {probePath2}");
                        return(Assembly.LoadFile(probePath2));
                    }

                    return(null);
                };
            }
        }
Beispiel #14
0
        private Assembly LoadWithAllReferencedAssebliesRecursive(string assemblyPath)
        {
            Assembly assembly = null;

            if (File.Exists(assemblyPath))
            {
                // assembly = new AssemblyResolver(assemblyPath, _logger).Assembly;
                assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
                var dependencyContext = DependencyContext.Load(assembly);

                var assemblyResolver = new CompositeCompilationAssemblyResolver
                                           (new ICompilationAssemblyResolver[]
                {
                    new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(assemblyPath)),
                    new ReferenceAssemblyPathResolver(),
                    new PackageCompilationAssemblyResolver()
                });
                var loadContext = AssemblyLoadContext.GetLoadContext(assembly);

                //These event handler required for load modules dependencies (packages and libraries). It is the best solution what I've found.
                //https://www.codeproject.com/Articles/1194332/Resolving-Assemblies-in-NET-Core
                //https://github.com/dotnet/corefx/issues/11639
                //https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/assemblyloadcontext.md
                //https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/corehost.md
                loadContext.Resolving += (context, assemblyName) =>
                {
                    bool assemblyPredicate(RuntimeLibrary runtime)
                    {
                        var result = runtime.Name.EqualsInvariant(assemblyName.Name);

                        if (result)
                        {
                            //Need to do an additional comparison by version because modules can use different versions
                            if (Version.TryParse(runtime.Version, out Version version))
                            {
                                result = new SemanticVersion(assemblyName.Version).IsCompatibleWith(new SemanticVersion(version));
                            }
                        }
                        return(result);
                    }

                    _logger.LogDebug($"Trying to resolve {assemblyName} in the {assembly.GetName().Name} dependencies");

                    var library = dependencyContext.RuntimeLibraries.FirstOrDefault(assemblyPredicate);
                    if (library != null)
                    {
                        var wrapper = new CompilationLibrary(
                            library.Type,
                            library.Name,
                            library.Version,
                            library.Hash,
                            library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
                            library.Dependencies,
                            library.Serviceable);

                        var assemblies = new List <string>();
                        assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies);
                        if (assemblies.Count > 0)
                        {
                            _logger.LogDebug($"Load assembly {assemblyName} from {assemblies[0]}");

                            return(context.LoadFromAssemblyPath(assemblies[0]));
                        }
                    }
                    return(null);
                };
            }
            return(assembly);
        }