【问题标题】:MEF and DirectoryCatalogMEF 和目录目录
【发布时间】:2011-10-08 20:40:47
【问题描述】:

如果目录不存在,有没有办法安全地使用 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);

但是如果目录不存在就会抛出异常,我想忽略这个错误。

【问题讨论】:

  • 在设置AggregateCatalog之前是否有不能只检查目录存在的原因?
  • 我愿意,但 DirectoryCatalog 中似乎内置了一些不错的逻辑,用于获取正确的路径(不仅仅是当前目录)。有谁知道它的用途吗? Assembly.Location?
  • 我对下面的答案发表了评论,但我也会在这里提到它......你不应该仅仅依靠检查目录是否存在。您应该考虑您希望处理的任何 IOExceptions(即,如果目录不存在,或者文件是否被锁定,或者 UAT 等)

标签: c# .net ioc-container mef


【解决方案1】:

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

根据the documentation

路径必须是绝对的或相对于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);  

【讨论】:

  • 见我上面的评论。 DirectoryCatalog 用什么方法展开全路径?
  • 相对于 System.AppDomain.BaseDirectory 或绝对或相对。
  • 已将您标记为答案。我在您对我使用的内容的回答中更新了您的代码。
  • 你不应该依赖诸如Directory.Exists(path)之类的竞争条件检查。在该调用和下一次调用之间,目录可能不存在。相反,使用异常处理来捕获可能的异常并适当地处理它......请参阅此答案:stackoverflow.com/a/9003962/347172
  • Directory.CreateDirectory 将在存在检查和 createdirectory 调用之间创建目录的可能性很小的情况下失败。所以,是的,在这段代码周围或调用堆栈的某个地方应该有一个 try catch 块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多