Handle ReflectionTypeLoadException during MEF composition

前端 未结 3 1985
我寻月下人不归
我寻月下人不归 2020-12-13 14:18

I am using a DirectoryCatalog in MEF to satisfy imports in my application. However, there are sometimes obfuscated assemblies in the directory that cause a

3条回答
  •  感动是毒
    2020-12-13 14:58

    To save others from writing their own implementation of the SafeDirectoryCatalog, here is the one I came up with based upon Wim Coenen's suggestions:

    public class SafeDirectoryCatalog : ComposablePartCatalog
    {
        private readonly AggregateCatalog _catalog;
    
        public SafeDirectoryCatalog(string directory)
        {
            var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);
    
            _catalog = new AggregateCatalog();
    
            foreach (var file in files)
            {
                try
                {
                    var asmCat = new AssemblyCatalog(file);
    
                    //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 (asmCat.Parts.ToList().Count > 0)
                        _catalog.Catalogs.Add(asmCat);
                }
                catch (ReflectionTypeLoadException)
                {
                }
                catch (BadImageFormatException)
                {
                }
            }
        }
        public override IQueryable Parts
        {
            get { return _catalog.Parts; }
        }
    }
    

提交回复
热议问题