MEF和DirectoryCatalog

时间:2011-07-19 20:00:27

标签: c# .net ioc-container mef

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

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

1 个答案:

答案 0 :(得分:9)

显然不会抛出异常。只需在运行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);