/// <summary> /// Releases the unmanaged resources used by the <see cref="ComposablePartCatalog" /> and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (disposing && !_isDisposed) { AssemblyCatalog catalogs = null; try { lock (_thisLock) { if (!_isDisposed) { catalogs = _catalog; _catalog = null; _isDisposed = true; } } } finally { if (catalogs != null) { catalogs.Dispose(); } } } } finally { base.Dispose(disposing); } }
/// <summary> /// Override to configure the framework and setup your IoC container. /// </summary> protected override void Configure() { var aggassemblyCatalog = new AggregateCatalog( AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>() ); var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll", SearchOption.TopDirectoryOnly); foreach (var file in files) { var assemblyCatalog = new AssemblyCatalog(file); // Force MEF to load the plug-in and figure out if there are any exports // good assemblies will not throw the RTLE exception and can be added to the catalog if (assemblyCatalog.Parts.Any()) { aggassemblyCatalog.Catalogs.Add(assemblyCatalog); } else { assemblyCatalog.Dispose(); } } this.container = new CompositionContainer(aggassemblyCatalog); this.container.ComposeExportedValue <IWindowManager>(new WindowManager()); this.container.ComposeExportedValue <IEventAggregator>(new EventAggregator()); var batch = new CompositionBatch(); batch.AddExportedValue(this.container); this.container.Compose(batch); }
public void Dispose() { if (_container != null) { _container.Dispose(); } if (_catalog != null) { _catalog.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { catalog.Dispose(); compositionContainer.Dispose(); } } disposed = true; }
/// <summary> /// Adds all exported types in the <paramref name="assembly"/> /// to the catalog. /// </summary> /// <param name="assembly">Must not be null.</param> public void AddAllMarkedTypesInAssembly(Assembly assembly) { Contract.Requires(assembly != null); Check.IfArgumentNull(assembly, "assembly"); ThrowIfDisposed(); var cat = new AssemblyCatalog(assembly); try { Contract.Assume(this.catalog.Catalogs != null); this.catalog.Catalogs.Add(cat); } catch { cat.Dispose(); throw; } }
/// <summary> /// This method creates an aggregate catalog for each located assembly /// in the specified directory. We internally handle exceptions here so /// unloadable assemblies are ignored. /// </summary> /// <param name="directoryName">Directory to probe</param> /// <param name="fileSpec">File specification</param> /// <returns>Catalog</returns> private static AggregateCatalog GetCatalogForDirectoryFileSpec(string directoryName, string fileSpec) { string[] files = Directory.GetFiles(directoryName, fileSpec, SearchOption.TopDirectoryOnly); AggregateCatalog aggCat = new AggregateCatalog(); foreach (string file in files) { try { var name = AssemblyName.GetAssemblyName(file); if (name != null) { var asm = Assembly.Load(name); if (asm != null) { // Create an assembly catalog -- only keep it around if we have // parts to resolve or needed parts inside it. var catalog = new AssemblyCatalog(asm); if (catalog.Parts.Any()) { aggCat.Catalogs.Add(catalog); } else { catalog.Dispose(); } } } } catch (Exception ex) { // Ignore if we cannot load the assembly. Debug.WriteLine(ex.ToString()); } } return(aggCat); }
internal static Collection <T> GetExportedPlugins <T>(Assembly assembly) { Collection <T> plugins = new Collection <T>(); AssemblyCatalog catalog = null; CompositionContainer container = null; try { catalog = new AssemblyCatalog(assembly); container = new CompositionContainer(catalog); FillExportedPlugins <T>(container, plugins); } catch (Exception e) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, e.Message, new ExceptionInfo(e)); } finally { catalog.Dispose(); container.Dispose(); } return(plugins); }
/// <summary> /// This adds assembly catalogs to the given aggregate catalog for the given folder and all of its /// subfolders recursively. /// </summary> /// <param name="catalog">The aggregate catalog to which the assembly catalogs are added.</param> /// <param name="folder">The root folder to search. It and all subfolders recursively will be searched /// for assemblies to add to the aggregate catalog.</param> /// <param name="searchedFolders">A hash set of folders that have already been searched and added.</param> /// <param name="includeSubfolders">True to search subfolders recursively, false to only search the given /// folder.</param> /// <remarks>It is done this way to prevent a single assembly that would normally be discovered via a /// directory catalog from preventing all assemblies from loading if it cannot be examined when the parts /// are composed (i.e. trying to load a Windows Store assembly on Windows 7).</remarks> private static void AddAssemblyCatalogs(AggregateCatalog catalog, string folder, HashSet <string> searchedFolders, bool includeSubfolders) { if (!String.IsNullOrWhiteSpace(folder) && Directory.Exists(folder) && !searchedFolders.Contains(folder)) { foreach (var file in Directory.EnumerateFiles(folder, "*.dll")) { try { var asmCat = new AssemblyCatalog(file); // Force MEF to load the assembly and figure out if there are any exports. Valid // assemblies won't throw any exceptions and will contain parts and will be added to // the catalog. Use Count() rather than Any() to ensure it touches all parts in case // that makes a difference. if (asmCat.Parts.Count() > 0) { catalog.Catalogs.Add(asmCat); } else { asmCat.Dispose(); } } catch (FileNotFoundException ex) { // Ignore the errors we may expect to see but log them for debugging purposes System.Diagnostics.Debug.WriteLine(ex); } catch (FileLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (BadImageFormatException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (IOException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (System.Security.SecurityException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (UnauthorizedAccessException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (TypeLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (ReflectionTypeLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); foreach (var lex in ex.LoaderExceptions) { System.Diagnostics.Debug.WriteLine(lex); } } } // Enumerate subfolders separately so that we can skip future requests for the same folder if (includeSubfolders) { try { foreach (string subfolder in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories)) { AddAssemblyCatalogs(catalog, subfolder, searchedFolders, false); } } catch (IOException ex) { System.Diagnostics.Debug.WriteLine(ex); } }
/// <summary> /// This adds assembly catalogs to the given aggregate catalog for the given folder and all of its /// subfolders recursively. /// </summary> /// <param name="catalog">The aggregate catalog to which the assembly catalogs are added.</param> /// <param name="folder">The root folder to search. It and all subfolders recursively will be searched /// for assemblies to add to the aggregate catalog.</param> /// <param name="searchedFolders">A hash set of folders that have already been searched and added.</param> /// <param name="includeSubfolders">True to search subfolders recursively, false to only search the given /// folder.</param> /// <param name="resolver">A component assembly resolver for finding dependency assemblies</param> /// <param name="cancellationToken">An optional cancellation token or null if not supported by the caller.</param> /// <remarks>It is done this way to prevent a single assembly that would normally be discovered via a /// directory catalog from preventing all assemblies from loading if it cannot be examined when the parts /// are composed (i.e. trying to load a Windows Store assembly on Windows 7).</remarks> private static void AddAssemblyCatalogs(AggregateCatalog catalog, string folder, HashSet <string> searchedFolders, bool includeSubfolders, ComponentAssemblyResolver resolver, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!String.IsNullOrWhiteSpace(folder) && Directory.Exists(folder) && !searchedFolders.Contains(folder)) { searchedFolders.Add(folder); // When debugging components, there may be a copy in the .\obj folder which tends to get found // later so it is used rather than the one in the .\bin folder which is actually being debugged. // If this is an .\obj folder and a .\bin folder has already been seen in the same location, // ignore it. if (folder.EndsWith("\\obj", StringComparison.OrdinalIgnoreCase) && searchedFolders.Contains( Path.Combine(Path.GetDirectoryName(folder), "bin"))) { return; } bool hadComponents = false; foreach (var file in Directory.EnumerateFiles(folder, "*.dll")) { if (cancellationToken != CancellationToken.None) { cancellationToken.ThrowIfCancellationRequested(); } try { var asmCat = new AssemblyCatalog(file); // Force MEF to load the assembly and figure out if there are any exports. Valid // assemblies won't throw any exceptions and will contain parts and will be added to // the catalog. Use Count() rather than Any() to ensure it touches all parts in case // that makes a difference. if (asmCat.Parts.Count() > 0) { catalog.Catalogs.Add(asmCat); hadComponents = true; } else { asmCat.Dispose(); } } // Ignore the errors we may expect to see but log them for debugging purposes catch (ArgumentException ex) { // These can occur if it tries to load a foreign framework assembly (i.e. .NETStandard) // In this case, the inner exception will be the bad image format exception. If not, // report the issue. if (!(ex.InnerException is BadImageFormatException)) { throw; } System.Diagnostics.Debug.WriteLine(ex); } catch (FileNotFoundException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (FileLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (BadImageFormatException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (IOException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (System.Security.SecurityException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (UnauthorizedAccessException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (TypeLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (ReflectionTypeLoadException ex) { System.Diagnostics.Debug.WriteLine(ex); foreach (var lex in ex.LoaderExceptions) { System.Diagnostics.Debug.WriteLine(lex); } } } // Track folders with components so that we can search them for dependencies later if needed if (hadComponents) { resolver.AddFolder(folder); } // Enumerate subfolders separately so that we can skip future requests for the same folder if (includeSubfolders) { try { foreach (string subfolder in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories)) { AddAssemblyCatalogs(catalog, subfolder, searchedFolders, false, resolver, cancellationToken); } } catch (IOException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (System.Security.SecurityException ex) { System.Diagnostics.Debug.WriteLine(ex); } catch (UnauthorizedAccessException ex) { System.Diagnostics.Debug.WriteLine(ex); } } } }
private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable <string> enumerateFiles, IConsole console) { foreach (var item in enumerateFiles) { AssemblyCatalog assemblyCatalog = null; try { assemblyCatalog = new AssemblyCatalog(item); // get the parts - throw if something went wrong var parts = assemblyCatalog.Parts; // load all the types - throw if assembly cannot load (missing dependencies is a good example) var assembly = Assembly.LoadFile(item); assembly.GetTypes(); catalog.Catalogs.Add(assemblyCatalog); } catch (BadImageFormatException ex) { if (assemblyCatalog != null) { assemblyCatalog.Dispose(); } // Ignore if the dll wasn't a valid assembly console.WriteWarning(ex.Message); } catch (FileLoadException ex) { // Ignore if we couldn't load the assembly. if (assemblyCatalog != null) { assemblyCatalog.Dispose(); } var message = string.Format(LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtension)), item); console.WriteWarning(message); console.WriteWarning(ex.Message); } catch (ReflectionTypeLoadException rex) { // ignore if the assembly is missing dependencies var resource = LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtensionDuringMefComposition)); var perAssemblyError = string.Empty; if (rex?.LoaderExceptions.Length > 0) { var builder = new StringBuilder(); builder.AppendLine(string.Empty); var errors = rex.LoaderExceptions.Select(e => e.Message).Distinct(StringComparer.Ordinal); foreach (var error in errors) { builder.AppendLine(error); } perAssemblyError = builder.ToString(); } var warning = string.Format(resource, item, perAssemblyError); console.WriteWarning(warning); } } }
private void Window_Closed(object sender, EventArgs e) { //clean up _container.Dispose(); _catalog.Dispose(); }