Joshua Ashton
Joshua Ashton

Reputation: 58

Using MEF to interact with events

I've recently looked into using MEF in order to build a plugin framework and also read quite a few articles and followed tutorials however what I'm attempting to achieve (and i haven't seen an example of this yet) is to provide an access point so i can load plugins from a set directory at the point of (for example) form loads, in order to alter the controls or prevent load ect or another example would be button clicks in order to extent or once again prevent standard functionality from taking place. Could anyone point me in the direction of other resources or provide a simple example explaining how this could be accomplished?

TIA

Upvotes: 1

Views: 203

Answers (1)

denys-vega
denys-vega

Reputation: 3697

This is a simple implementation example. First add the reference System.ComponentModel.Composition to the project.

Declare the Plugin interface:

[InheritedExport]
public interface IPlugin
{
    string Name { get; }
}

In the same or another assembly, implement the bellow interface.

public class Plugin1 : IPlugin
{
    public string Name
    {
        get { return "Plugin#1"; }
    }
}

Later build your Catalog using DirectoryCatalog and AssemblyCatalog.

public class CatalogManager : IDisposable
{
    [ImportMany(typeof (IPlugin), AllowRecomposition = true)] 
    private IEnumerable<IPlugin> _plugins;

    private CompositionContainer _container;

    public CompositionContainer Container
    {
        get { return _container; }
    }

    public IEnumerable<IPlugin> Plugins
    {
        set { _plugins = value; }
    }

    private CatalogManager(string pluginsDir)
    {
        var catalog = new AggregateCatalog();

        //--load all plugin from plugin directory
        if (Directory.Exists(pluginsDir))
            catalog.Catalogs.Add(new DirectoryCatalog(pluginsDir));

        //--load all plugin from executing assembly
        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

        Initialize(catalog);
    }

    private void Initialize(AggregateCatalog catalog)
    {
        _container = new CompositionContainer(catalog);

        _container.ComposeParts(this);
    }

    public void Dispose()
    {
        if (_container == null)
            return;

        _container.Dispose();
        _container = null;
    }
}

Upvotes: 3

Related Questions