jonathanpeppers
jonathanpeppers

Reputation: 26495

MEF and DirectoryCatalog

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.

Upvotes: 9

Views: 9252

Answers (1)

Jon Raynor
Jon Raynor

Reputation: 3892

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

Upvotes: 9

Related Questions