How to communicate between two extensions

I was asked by one developer how he might share data between two (DotSpatial) extensions and “light up” when the second extension was available.

This quick example shows exporting a method and importing it elsewhere by using a contract name. As long as the contract names and the signatures match, the export will be made available to the matching import by MEF.

public class MefImportPlugin : Extension
{
    public override void Activate()
    {
        App.HeaderControl.Add(new SimpleActionItem("Retrieve Message", ButtonClick));
        base.Activate();
    }

    public override void Deactivate()
    {
        App.HeaderControl.RemoveAll();
        base.Deactivate();
    }

    public void ButtonClick(object sender, EventArgs e)
    {
        var message = GetLayerCountMessage();
        System.Diagnostics.Trace.WriteLine(message);
    }

    [System.ComponentModel.Composition.Import("LayerCount.Message")]
    public Func<string> GetLayerCountMessage
    {
        get;
        set;
    }
}

 

public class MefExportPlugin : Extension
 {
     private string _Message;
     public override void Activate()
     {
         App.HeaderControl.Add(new SimpleActionItem("Show Layer Count", ButtonClick));
         base.Activate();
     }

     public override void Deactivate()
     {
         App.HeaderControl.RemoveAll();
         base.Deactivate();
     }

     public void ButtonClick(object sender, EventArgs e)
     {
         _Message = String.Format("Number of Layers: {0}", App.Map.Layers.Count);
         App.ProgressHandler.Progress(null, 0, _Message);
     }

     [System.ComponentModel.Composition.Export("LayerCount.Message")]
     public string Message()
     {
         return _Message;
     }
 }

These are standard Managed Extension Framework capabilities, so you can find more documentation by searching for MEF.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s