Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 708
jonathanpeppers Avatar asked Jul 19 '11 20:07

jonathanpeppers


1 Answers

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);  
like image 177
Jon Raynor Avatar answered Oct 20 '22 00:10

Jon Raynor