Search code examples
c#pluginsmefcomposition

Why is getting Exports in MEF so slow?


I create a MEF container as follows:

        //Compose Plugins
        var aggregateCatalog = new AggregateCatalog();

        IEnumerable<string> directories = FileIO.GetAllSubDirectories(PluginRootDirectory);
        foreach (string directory in directories)
        {
            var catalog = new DirectoryCatalog(directory);
            aggregateCatalog.Catalogs.Add(catalog);
        }

        Container = new CompositionContainer(aggregateCatalog);
        Container.ComposeParts(Container);

I then try to get exports as follows:

    public Dictionary<string, T> GetPlugins<T>()
    {
        var exports = Container.GetExports<T, IPluginAttribute>();
        return exports.ToDictionary(i => i.Metadata.PluginName, i => i.Value);
    }
  • The first code snippet is executed in the constructor.
  • The second code snippet requests plugins of a specific type and is always executed after the first code snipped executed.
  • Executing the second code snippet for the first time takes very long time; however, subsequent requests run fast.

Question: How can I ensure the container is composed before requesting exports/plugins? I want even the first request GetPlugins<T>() to run fast. I can live with longer initialization times but right now it seems the composition of the container is delayed until actually requesting exported plugins.


Solution

  • MEF takes time if there are many files to parse via directory catalog.It will try to parse ALL the binares in the directory whether managed or unmanaged.

    Also it will cache class not marked as Export too as MEF allows you to import classes by name even if they dont have a Export attribute.

    Try having only single dummy dll with your blank classes to see if the issue is with too many files or MEF.