MEF和DirectoryCatalog

jon*_*ers 9 .net c# mef ioc-container

如果目录不存在,有没有办法安全地使用DirectoryCatalog来处理?

这是我的容器设置方式的代码示例:

    //Create an assembly catalog of the assemblies with exports
    var catalog = new AggregateCatalog(
        new AssemblyCatalog(Assembly.GetExecutingAssembly()),
        new AssemblyCatalog(Assembly.Load("My.Second.Assembly")),
        new DirectoryCatalog("Plugins", "*.dll"));

    //Create a composition container
    var container = new CompositionContainer(catalog);
Run Code Online (Sandbox Code Playgroud)

但是如果目录不存在则抛出异常,我想忽略该错误.

Jon*_*nor 9

显然不会抛出异常.只需在运行MEF容器设置之前创建目录,然后就不会抛出任何错误.

根据文件:

路径必须是绝对的或相对的AppDomain.BaseDirectory.

PsuedoCode进行目录检查:

    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");

    //Check the directory exists
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

    //Create an assembly catalog of the assemblies with exports
    var catalog = new AggregateCatalog(
        new AssemblyCatalog(Assembly.GetExecutingAssembly()),
        new AssemblyCatalog(Assembly.Load("My.Other.Assembly")),
        new DirectoryCatalog(path, "*.dll"));

    //Create a composition container
    _container = new CompositionContainer(catalog);  
Run Code Online (Sandbox Code Playgroud)

  • 你永远不应该依赖于竞争条件检查,例如`Directory.Exists(path)`.在该调用和下一次调用之间,该目录可能不存在.相反,使用异常处理来捕获可能的异常并适当地处理它...请参阅以下答案:http://stackoverflow.com/a/9003962/347172 (2认同)