public void EnableModule(string moduleName) { if (!PluginsLoadContexts.Any(moduleName)) { var context = new CollectibleAssemblyLoadContext(); var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll"; var referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}"; using (var fs = new FileStream(filePath, FileMode.Open)) { var assembly = context.LoadFromStream(fs); _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly); var controllerAssemblyPart = new MyAssemblyPart(assembly); AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath); _partManager.ApplicationParts.Add(controllerAssemblyPart); PluginsLoadContexts.AddPluginContext(moduleName, context); } } else { var context = PluginsLoadContexts.GetContext(moduleName); var controllerAssemblyPart = new MyAssemblyPart(context.Assemblies.First()); _partManager.ApplicationParts.Add(controllerAssemblyPart); } ResetControllActions(); }
public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly) { var references = assembly.GetReferencedAssemblies(); foreach (var item in references) { var name = item.Name; var version = item.Version.ToString(); var stream = _referenceContainer.GetStream(name, version); if (stream != null) { _logger.LogDebug($"Found the cached reference '{name}' v.{version}"); context.LoadFromStream(stream); } else { if (IsSharedFreamwork(name)) { continue; } var dllName = $"{name}.dll"; var filePath = $"{moduleFolder}\\{dllName}"; if (!File.Exists(filePath)) { _logger.LogWarning($"The package '{dllName}' is missing."); continue; } using (var fs = new FileStream(filePath, FileMode.Open)) { var referenceAssembly = context.LoadFromStream(fs); var memoryStream = new MemoryStream(); fs.Position = 0; fs.CopyTo(memoryStream); fs.Position = 0; memoryStream.Position = 0; _referenceContainer.SaveStream(name, version, memoryStream); LoadStreamsIntoContext(context, moduleFolder, referenceAssembly); } } } }
public static void AddPluginContext(string pluginName, CollectibleAssemblyLoadContext context) { _pluginContexts.Add(pluginName, context); }