public SafeDirectoryCatalog(string directory,
                                    Func <Type, bool> typeFilter        = null,
                                    ReflectionContext reflectionContext = null,
                                    Func <string, bool> fileFilter      = null)
        {
            // cf.: http://stackoverflow.com/a/4475117/2592915
            _dirInfo = new DirectoryInfo(directory);
            Catalog  = new AggregateCatalog();

            var safeFileFilter = fileFilter ?? (fileName => true);
            var files          = _dirInfo.EnumerateFiles("*.dll", SearchOption.AllDirectories)
                                 .Where(file => safeFileFilter(file.FullName));

            foreach (var file in files)
            {
                try
                {
                    var catalog = new SafeAssemblyCatalog(file.FullName, typeFilter, reflectionContext);

                    //Force MEF to load the plugin and figure out if there are any exports.
                    // good assemblies will not throw the RTLE exception and can be added to the catalog
                    if (catalog.Parts.ToList().Count <= 0)
                    {
                        continue;
                    }

                    Catalog.Catalogs.Add(catalog);
                    Assemblies.Add(catalog.Assembly);
                }
                catch (Exception ex) when(ex is ReflectionTypeLoadException || ex is BadImageFormatException)
                {
                    Trace.WriteLine($"Could not load '{file.FullName}': {ex}");
                }
            }
        }
Exemple #2
0
        public void Use_type_filter()
        {
            var expected = typeof(SafeAssemblyCatalog_Should);

            using (var sut = new SafeAssemblyCatalog(Assembly.GetExecutingAssembly(), type => type == expected))
            {
                // "is a" ReflectionComposablePartDefinition(), so we use "ToString()" to check
                // cf.: https://mef.codeplex.com/SourceControl/latest#redist/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs
                var part = sut.Parts.Single();
                part.ToString().Should().Be(expected.FullName);


                var importDefinition = new ImportDefinition(e => false, "contract", ImportCardinality.ExactlyOne, false,
                                                            false);
                sut.GetExports(importDefinition).Should().BeEmpty();
            }
        }