protected override Assembly Load(AssemblyName assemblyName)
        {
            resolver = _resolver;
            if (resolver == null)
            {
                if (!_DependencyDLL.TryGetValue(assemblyName.Name, out resolver))
                {
                    string file = null;
                    file = DependencyDir.SelectMany(X => Directory.GetFileSystemEntries(X, assemblyName.Name + ".dll")).FirstOrDefault();
                    if (file == null)
                    {
                        file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName.Name + ".dll");
                    }
                    if (!File.Exists(file))
                    {
                        return(null);
                    }
                    resolver = new AssemblyDependencyResolver(file);
                    _DependencyDLL[assemblyName.Name] = resolver;
                }
            }
            string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);

            if (assemblyPath != null)
            {
                return(LoadFromAssemblyPath(assemblyPath));
            }

            return(null);
        }
示例#2
0
        public ManagedLoadContext(string mainAssemblyPath,
                                  IReadOnlyDictionary <string, ManagedLibrary> managedAssemblies,
                                  IReadOnlyDictionary <string, NativeLibrary> nativeLibraries,
                                  IReadOnlyCollection <string> privateAssemblies,
                                  IReadOnlyCollection <string> defaultAssemblies,
                                  IReadOnlyCollection <string> additionalProbingPaths,
                                  IReadOnlyCollection <string> resourceProbingPaths,
                                  bool preferDefaultLoadContext,
                                  bool isCollectible, ICollection <string> sharedAssemblyPrefixes)
            : base(Path.GetFileNameWithoutExtension(mainAssemblyPath), isCollectible)
        {
            if (resourceProbingPaths == null)
            {
                throw new ArgumentNullException(nameof(resourceProbingPaths));
            }

            _mainAssemblyPath         = mainAssemblyPath ?? throw new ArgumentNullException(nameof(mainAssemblyPath));
            _dependencyResolver       = new AssemblyDependencyResolver(mainAssemblyPath);
            _basePath                 = Path.GetDirectoryName(mainAssemblyPath) ?? throw new ArgumentException(nameof(mainAssemblyPath));
            _managedAssemblies        = managedAssemblies ?? throw new ArgumentNullException(nameof(managedAssemblies));
            _privateAssemblies        = privateAssemblies ?? throw new ArgumentNullException(nameof(privateAssemblies));
            _defaultAssemblies        = defaultAssemblies ?? throw new ArgumentNullException(nameof(defaultAssemblies));
            _nativeLibraries          = nativeLibraries ?? throw new ArgumentNullException(nameof(nativeLibraries));
            _additionalProbingPaths   = additionalProbingPaths ?? throw new ArgumentNullException(nameof(additionalProbingPaths));
            _preferDefaultLoadContext = preferDefaultLoadContext;
            _sharedAssemblyPrefixes   = sharedAssemblyPrefixes;

            _resourceRoots = new[] { _basePath }
            .Concat(resourceProbingPaths)
            .ToArray();
        }
        public CommandLoadContext(string mainAssembly)
            : base(true)
        {
            _resolver = new AssemblyDependencyResolver(mainAssembly);

            MainAssembly = LoadFromAssemblyPath(mainAssembly);
        }
示例#4
0
 private LoadContext(string parentAssembly)
 {
     this.PathToParentAssembly = parentAssembly;
     this.resolver             = new AssemblyDependencyResolver(this.PathToParentAssembly);
     this.fallbackPaths        = new HashSet <string>();
     this.Resolving           += this.OnResolving;
 }
示例#5
0
        public PluginLoadContext(string pluginPath)
        {
            _resolver = new AssemblyDependencyResolver(pluginPath);

            Resolving += PluginLoadContext_Resolving;

            Default.Resolving += (context, assemblyName) =>
            {
                var assemblyFullName = PluginLoadContexts?.Select(o => o.BaseAssembly)?.FirstOrDefault(p => p.FullName == assemblyName.FullName);

                if (assemblyFullName != null)
                {
                    return(Assemblies.FirstOrDefault(p => p.FullName == assemblyName.FullName));
                }

                return(null);
            };

            //Default.Resolving += (context, assembly) =>
            //{
            //    return Assemblies.FirstOrDefault(p =>
            //    p.GetName().Name == assembly.Name &&
            //    p.GetName().Version == assembly.Version);
            //};
        }
 public override Task <Assembly> LoadPluginAssemblyAsync(IPluginLoadContext pluginLoadContext)
 {
     // contains rootpath + plugin folder + plugin assembly name
     // HostApplication/bin/Debug/netcoreapp3.0 + Plugins + Plugin.dll
     this.resolver = new AssemblyDependencyResolver(Path.Join(pluginLoadContext.PluginAssemblyPath, pluginLoadContext.PluginAssemblyName));
     return(base.LoadPluginAssemblyAsync(pluginLoadContext));
 }
示例#7
0
        public AssemblyDomain(string key) : base(isCollectible: true, name: key)
        {
            _load_resolver = new AssemblyDependencyResolver(AppDomain.CurrentDomain.BaseDirectory);


            DomainPath             = Path.Combine(DomainManager.CurrentPath, key);
            OutfileMapping         = new ConcurrentDictionary <string, Assembly>();
            PathMapping            = new ConcurrentDictionary <Assembly, string>();
            AssemblyMappings       = new ConcurrentDictionary <Assembly, AssemblyUnitInfo>();
            ShortReferenceMappings = new ConcurrentDictionary <string, PortableExecutableReference>();

            DomainManager.Add(key, this);

            if (key == "Default")
            {
                var _ref = DependencyContext.Default.CompileLibraries
                           .SelectMany(cl => cl.ResolveReferencePaths())
                           .Select(asm =>
                {
                    var table = MetadataReference.CreateFromFile(asm);
                    ShortReferenceMappings[Path.GetFileName(asm)] = table;
                    return(table);
                });

                ReferencesCache                = new LinkedList <PortableExecutableReference>(_ref);
                Default.Resolving             += Default_Resolving;
                Default.ResolvingUnmanagedDll += Default_ResolvingUnmanagedDll;
            }
            else
            {
                ReferencesCache = new LinkedList <PortableExecutableReference>();
            }
        }
示例#8
0
 public HostAssemblyLoadContext(string pluginPath) : base(isCollectible: true)
 {
     _resolver       = new AssemblyDependencyResolver(pluginPath);
     _pluginDirFiles = new DirectoryInfo(pluginPath).GetFiles().ToDictionary(
         data => data.Name,
         data => data.FullName);
 }
示例#9
0
 internal AssemblyObject(AssemblyLoadContext context, AssemblyDependencyResolver resolver, Assembly rootAssembly, string path)
 {
     Context      = context;
     Resolver     = resolver;
     RootAssembly = rootAssembly;
     Path         = path;
 }
示例#10
0
        private static void LoadInMemoryAssemblyInContextImpl(IntPtr moduleHandle, IntPtr assemblyPath, AssemblyLoadContext?alc = null)
        {
            string?assemblyPathString = Marshal.PtrToStringUni(assemblyPath);

            if (assemblyPathString == null)
            {
                throw new ArgumentOutOfRangeException(nameof(assemblyPath));
            }

            // We don't cache the ALCs or resolvers here since each IJW assembly will call this method at most once
            // (the load process rewrites the stubs that call here to call the actual methods they're supposed to)
            if (alc is null)
            {
                alc = new IsolatedComponentLoadContext(assemblyPathString);
            }
            else if (alc == AssemblyLoadContext.Default)
            {
                var resolver = new AssemblyDependencyResolver(assemblyPathString);
                AssemblyLoadContext.Default.Resolving +=
                    [RequiresUnreferencedCode("C++/CLI is not trim-compatible", Url = "https://aka.ms/dotnet-illink/nativehost")]
                        (context, assemblyName) =>
                {
                    string?assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
                    return(assemblyPath != null
                            ? context.LoadFromAssemblyPath(assemblyPath)
                            : null);
                };
            }

            alc.LoadFromInMemoryModule(moduleHandle);
        }
示例#11
0
        //todo 需要watch
        private void Load()
        {
            //先卸载老的
            //todo 这里应该是先加载更新的,出了异常就还是用老的,加载成功则用新的,并卸载老的
            UnLoad();
            try
            {
                resolver                        = new AssemblyDependencyResolver(filepath);
                _AssemblyLoadContext            = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
                _AssemblyLoadContext.Resolving += _AssemblyLoadContext_Resolving;

                using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    _Assembly = _AssemblyLoadContext.LoadFromStream(fs);
                    var types = _Assembly.GetTypes();
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type item = types[i];
                        if (typeof(Service.Service).FullName == item.GetTypeInfo().FullName&& item.IsClass)
                        {
                            service = (IService)Activator.CreateInstance(item);
                        }
                    }
                }
                if (service == null)
                {
                    throw new Exception("not found class Service");
                }
            }
            catch (Exception ex) { throw new Exception(ex.Message); };
        }
示例#12
0
        // *******************************************************************
        // Constructors.
        // *******************************************************************

        #region Constructors

        /// <summary>
        /// This constructor creates a new instance of the <see cref="AssemblyLoader"/>
        /// class.
        /// </summary>
        /// <param name="baseDirectory">The base directory to use for resolving
        /// assemblies at runtime.</param>
        /// <param name="assemblyContextName">The name of the assembly loading
        /// context.</param>
        /// <param name="isCollectible">True to enable unloading assemblies from
        /// the loading context.</param>
        public AssemblyLoader(
            string baseDirectory,
            string assemblyContextName,
            bool isCollectible
            ) : base(assemblyContextName, isCollectible)
        {
            // Validate the parameters before attempting to use them.
            Guard.Instance().ThrowIfNullOrEmpty(
                baseDirectory,
                nameof(baseDirectory)
                ).ThrowIfInvalidFolderPath(
                baseDirectory,
                nameof(baseDirectory)
                );

            // Save the values.
            _baseDirectory           = baseDirectory;
            _dynamicDirectory        = AppDomain.CurrentDomain.DynamicDirectory;
            _relativeSearchDirectory = AppDomain.CurrentDomain.RelativeSearchPath;
            _applicationDirectory    = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            // Create the dependency resolver.
            _resolver = new AssemblyDependencyResolver(
                baseDirectory
                );
        }
示例#13
0
        public PluginLoadContext(PluginManager pluginManager, Plugin plugin) : base(EnvironmentConfig.ReloadEnabled)
        {
            this.pluginManager = pluginManager;
            this.plugin        = plugin;

            resolver = new AssemblyDependencyResolver(plugin.Path);
        }
示例#14
0
        public PluginAssemblyLoadContext(string mainAssemblyToLoadPath, string name, bool isCollectible = false) : base(name, isCollectible)
        {
            _resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath);

            this.Resolving += ResolveReference;
            this.Unloading += OnUnloading;
        }
示例#15
0
        public PluginLoadContext(DirectoryInfo thisPluginDirectory) : base(thisPluginDirectory.Name, false)
        {
            this.thisPluginDirectory = thisPluginDirectory;
            _thisPluginResolver      = new AssemblyDependencyResolver(this.thisPluginDirectory.FullName);

            Resolving += PluginLoadContext_Resolving;
        }
示例#16
0
        public static Assembly Load(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            path = PathUtils.GetRelativePath(Environment.CurrentDirectory, path);

            AssemblyLoadContext        alc = new AssemblyLoadContext(null, true);
            AssemblyDependencyResolver dr  = new AssemblyDependencyResolver(path);
            Assembly rootAss = alc.LoadFromAssemblyPath(Path.GetFullPath(path));

            Log.Core.Info($"[assembly loader] loaded assembly '{path}'");

            AssemblyObject assemblyObject = new AssemblyObject(alc, dr, rootAss, path);

            _assemblies.Add(path, assemblyObject);

            var assnArr = rootAss.GetReferencedAssemblies();

            for (int i = 0; i < assnArr.Length; i++)
            {
                LoadDependency(assnArr[i], assemblyObject);
            }

            return(rootAss);
        }
        protected override void Dispose(bool disposing)
        {
            if (!this.disposed && disposing)
            {
                this.disposing = true;

                GC.Collect();
                GC.WaitForPendingFinalizers();

                this.hostTypesProvider        = null;
                this.remoteTypesProvider      = null;
                this.dependencyPathProvider   = null;
                this.probingPathsProvider     = null;
                this.runtimePlatformContext   = null;
                this.depsFileProvider         = null;
                this.pluginDependencyResolver = null;
                this.pluginDependencyContext  = null;
                this.assemblyLoadStrategy     = null;
                this.resolver = null;

                foreach (var nativeAssembly in this.loadedNativeLibraries)
                {
                    this.nativeAssemblyUnloader.UnloadNativeAssembly(nativeAssembly.Key, nativeAssembly.Value);
                }

                this.nativeAssemblyUnloader = null;
                this.loadedNativeLibraries  = null;
            }
            this.disposed = true;
        }
示例#18
0
            public AnalyzerLoadContext(string assemblyPath)
            {
                var assemblyDirectory = Path.GetDirectoryName(assemblyPath);

                if (assemblyDirectory is null)
                {
                    throw new InvalidOperationException($"Assembly path invalid '{assemblyPath}'");
                }

                var analyzerDirectory = new DirectoryInfo(assemblyDirectory);

                // Analyzer packages will put language specific assemblies in subfolders.
                if (analyzerDirectory.Name == "cs" || analyzerDirectory.Name == "vb")
                {
                    // Get the root analyzer folder.
                    analyzerDirectory = analyzerDirectory.Parent;
                }

                if (analyzerDirectory is null)
                {
                    throw new InvalidOperationException($"Could not get parent directory for '{assemblyPath}'");
                }

                AssemblyFolderPath = analyzerDirectory.FullName;
                DependencyResolver = new AssemblyDependencyResolver(assemblyPath);
            }
示例#19
0
 public TestAssemblyLoadContext(string name, bool isCollectible, string mainAssemblyToLoadPath = null) : base(name, isCollectible)
 {
     if (!PlatformDetection.IsBrowser)
     {
         _resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath ?? Assembly.GetExecutingAssembly().Location);
     }
 }
 public PluginAssemblyLoadContext(PluginInfo info, PluginContext alcContext)
     : base($"{nameof(LazyMan)}:Plugin:{info.PluginName}", true)
 {
     PluginInfo = info ?? throw new ArgumentNullException(nameof(info));
     ALCContext = alcContext ?? throw new ArgumentNullException(nameof(alcContext));
     try
     {
         // resolver have bug for fileName
         Resolver = new AssemblyDependencyResolver(info.PluginDll);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e);
     }
     //using (this.EnterContextualReflection())
     //{
     // if this load fail, then throw
     EntryAssemlby = this.LoadFromAssemblyPath(info.PluginDll);
     //foreach (var asln in EntryAssemlby.GetReferencedAssemblies())
     //{
     //    Console.WriteLine("#########################################");
     //    try
     //    {
     //        Console.WriteLine(asln.Name);
     //        this.LoadFromAssemblyName(asln);
     //    }
     //    catch (Exception e)
     //    {
     //        Console.WriteLine("can not load " + asln.Name);
     //        Console.WriteLine(e);
     //    }
     //    Console.WriteLine("#########################################");
     //}
     //}
 }
示例#21
0
        public ManagedLoadContext(string mainAssemblyPath,
                                  IReadOnlyDictionary <string, ManagedLibrary> managedAssemblies,
                                  IReadOnlyDictionary <string, NativeLibrary> nativeLibraries,
                                  IReadOnlyCollection <string> privateAssemblies,
                                  IReadOnlyCollection <string> defaultAssemblies,
                                  IReadOnlyCollection <string> additionalProbingPaths,
                                  IReadOnlyCollection <string> resourceProbingPaths,
                                  bool preferDefaultLoadContext,
                                  bool isCollectible)
#if FEATURE_UNLOAD
            : base(isCollectible)
#endif
        {
            if (resourceProbingPaths == null)
            {
                throw new ArgumentNullException(nameof(resourceProbingPaths));
            }

            _mainAssemblyPath = mainAssemblyPath ?? throw new ArgumentNullException(nameof(mainAssemblyPath));
#if FEATURE_NATIVE_RESOLVER
            _dependencyResolver = new AssemblyDependencyResolver(mainAssemblyPath);
#endif
            _basePath                 = Path.GetDirectoryName(mainAssemblyPath);
            _managedAssemblies        = managedAssemblies ?? throw new ArgumentNullException(nameof(managedAssemblies));
            _privateAssemblies        = privateAssemblies ?? throw new ArgumentNullException(nameof(privateAssemblies));
            _defaultAssemblies        = defaultAssemblies ?? throw new ArgumentNullException(nameof(defaultAssemblies));
            _nativeLibraries          = nativeLibraries ?? throw new ArgumentNullException(nameof(nativeLibraries));
            _additionalProbingPaths   = additionalProbingPaths ?? throw new ArgumentNullException(nameof(additionalProbingPaths));
            _preferDefaultLoadContext = preferDefaultLoadContext;

            _resourceRoots = new[] { _basePath }
            .Concat(resourceProbingPaths)
            .ToArray();
        }
示例#22
0
    public NatashaAssemblyDomain(string key) : base(key)
    {
#if !NETSTANDARD2_0
        DependencyResolver = new AssemblyDependencyResolver(AppDomain.CurrentDomain.BaseDirectory);
#endif
        DllAssemblies = new ConcurrentDictionary <string, Assembly>();
    }
示例#23
0
 private LoadContext(string parentAssembly)
 {
     this.PathToParentAssembly = parentAssembly ?? throw new ArgumentNullException(nameof(parentAssembly));
     this._Resolver            = new AssemblyDependencyResolver(this.PathToParentAssembly);
     this._FallbackPaths       = new HashSet <string>();
     this.Resolving           += this.OnResolving;
 }
示例#24
0
文件: LoadDll.cs 项目: chenxyzl/LinS
        public void LoadFile()
        {
            //先卸载老的
            //todo 这里应该是先加载更新的,出了异常就还是用老的,加载成功则用新的,并卸载老的
            UnLoad();
            try
            {
                resolver                        = new AssemblyDependencyResolver(filepath);
                _AssemblyLoadContext            = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
                _AssemblyLoadContext.Resolving += _AssemblyLoadContext_Resolving;

                using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    _Assembly = _AssemblyLoadContext.LoadFromStream(fs);
                    var types = _Assembly.GetTypes();
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type item = types[i];
                        if (item.GetInterface(typeName) != null && item.IsClass)
                        {
                            var ins = (T)Activator.CreateInstance(item);
                            ins.Load();
                            _instances.Add(ins);
                        }
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); };
        }
示例#25
0
        public AssemblyDomain(string key)
#if  !NETSTANDARD2_0
            : base(isCollectible: true, name: key)
#endif

        {
#if !NETSTANDARD2_0
            _resolver = new AssemblyDependencyResolver(AppDomain.CurrentDomain.BaseDirectory);
#else
            Name = key;
#endif

            DomainManagment.Add(key, this);
            TypeCache        = new HashSet <Type>();
            OutfileMapping   = new ConcurrentDictionary <string, Assembly>();
            AssemblyMappings = new ConcurrentDictionary <Assembly, AssemblyUnitInfo>();
            CanCover         = true;


            if (key == "Default")
            {
                var _ref = DependencyContext.Default.CompileLibraries
                           .SelectMany(cl => cl.ResolveReferencePaths())
                           .Select(asm => MetadataReference.CreateFromFile(asm));

                ReferencesCache = new HashSet <PortableExecutableReference>(_ref);
            }
            else
            {
                ReferencesCache = new HashSet <PortableExecutableReference>();
            }


            this.Unloading += AssemblyDomain_Unloading;
        }
 public PlugInLoadContext(
     string pluginPath,
     ICollection <string> plugInApiAssemblies)
 {
     _resolver = new AssemblyDependencyResolver(pluginPath);
     _plugInApiAssemblyNames = plugInApiAssemblies;
 }
示例#27
0
            protected override Assembly Load(AssemblyName assemblyName)
            {
                if (assemblyName.Name.StartsWith("System") || assemblyName.Name.StartsWith("Microsoft"))
                {
                    return(null);
                }

                var assembly = FindAssembly(_plugin, assemblyName);

                if (assembly == null)
                {
                    if (_resolver == null && _plugin._manifest.Assemblies != null && _plugin._manifest.Assemblies.Length > 0)
                    {
                        _resolver = new AssemblyDependencyResolver(_plugin._manifest.Assemblies[0].Location);
                    }

                    if (_resolver != null)
                    {
                        var filePath = _resolver.ResolveAssemblyToPath(assemblyName);

                        if (!string.IsNullOrEmpty(filePath))
                        {
                            assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(filePath);
                        }
                    }
                }

                return(assembly);
            }
示例#28
0
        public ApplicationContext(INegotiator negotiator, string executablesPath, string executableName)
        {
            this._Negotiator = negotiator;

            if (string.IsNullOrEmpty(executablesPath))
            {
                throw new ArgumentNullException(nameof(executablesPath));
            }
            if (string.IsNullOrEmpty(executableName))
            {
                throw new ArgumentNullException(nameof(executableName));
            }

            this.Resolving += this.ResolveAssembly;

            this._ExecutableName = executableName;
            this._ExecutablePath =
                Path.Combine(executablesPath, $"{this._ExecutableName}.dll");
            this._DependencyResolver = new AssemblyDependencyResolver(this._ExecutablePath);

            this._ExecutableInstances =
                new ConcurrentDictionary <Type, DomainExecutable>();

            this._AssemblyMethodLock = new object();
            this._AssemblyMethods    =
                new Dictionary <string, MethodInfo[]>();
        }
示例#29
0
        public override void AddReferencesFromDepsJsonFile(string path, params string[] excludePaths)
        {
            HashSet <string> exclude;

            if (excludePaths == default)
            {
                exclude = new HashSet <string>();
            }
            else
            {
                exclude = new HashSet <string>(excludePaths);
            }


#if !NETSTANDARD2_0
            _load_resolver = new AssemblyDependencyResolver(path);
            var newMapping = GetDictionary(_load_resolver);

            foreach (var item in newMapping)
            {
                if (!exclude.Contains(item.Value))
                {
                    ShortReferences.Add(item.Value);
                }
            }
#endif
        }
示例#30
0
        public AssemblyDomain(string key)
#if NETCOREAPP3_0
            : base(isCollectible: true, name: key)
#endif

        {
            LibPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NatashaLib", key);
            if (Directory.Exists(LibPath))
            {
                Directory.Delete(LibPath, true);
            }
            Directory.CreateDirectory(LibPath);


#if NETCOREAPP3_0
            _resolver = new AssemblyDependencyResolver(LibPath);
#endif

            ClassMapping = new ConcurrentDictionary <string, Assembly>();
            DynamicDlls  = new ConcurrentDictionary <string, Assembly>();


            var _ref = DependencyContext.Default.CompileLibraries
                       .SelectMany(cl => cl.ResolveReferencePaths())
                       .Select(asm => MetadataReference.CreateFromFile(asm));
            References      = new ConcurrentQueue <PortableExecutableReference>(_ref);
            this.Unloading += AssemblyDomain_Unloading;
        }