MEF 和 DirectoryCatalog

发布于 2024-11-25 06:30:04 字数 508 浏览 1 评论 0原文

有没有办法安全地使用 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);

但是如果目录不存在,则会引发异常,我想忽略该错误。

Is there a way to safely use DirectoryCatalog to handle if the directory doesn't exist?

Here a code example of how my container is setup:

    //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);

But an exception is thrown if the directory doesn't exist, and I would like to ignore that error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠北森屋 2024-12-02 06:30:04

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

根据文档

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

进行目录检查的伪代码:

    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);  

Apparently not if an exception is thrown. Just create the directory prior to running the MEF container setup and then no error will be thrown.

According to the documentation:

The path must be absolute or relative to AppDomain.BaseDirectory.

PsuedoCode to do a directory check:

    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);  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文