views:

63

answers:

1

I'm working on a Visual Studio Add-in for Visual Studio 2008 that display a treeview that provides a view on content in a server product. The server product contains different types of nodes, and each node has its own type of context menu (right click menu).

For new types of nodes and the actions connected to a node I currently just add code two my project. I would like to disconnect my node types and the actions available on a node in such a few that I can add nodes and entries to to context menu with a plugin model. MEF would probably be a good candidate. Does anyone have a good idea on how to implement this in a simple and straightforward way, so that especially the plugin developer does not have to do a lot of plumbing?

+1  A: 

I would provide a common library that both your code and the plugin libraries all link to (call this the Contract dependency). In there, define an interface for a node type, like INodeType. Also, consider implementing an AbstractNodeType in there that implements INodeType and provides some helpful properties that the plugin author can set in their constructor.

One of the properties of INodeType is a ContextMenu property that returns a windows forms context menu.

In your code make a property:

[Import("NodeTypes", typeof(INodeType))]
public IEnumerable<INodeType> extensionNodeTypes { get; set; }

You can just enumerate through that after you've composed.

In the plugin code, they would declare new node types something like this (may not compile):

[Export("NodeTypes", typeof(INodeType))]
public class SomeNodeType : AbstractNodeType
{
    public SomeNodeType()
    {
        this.ContextMenu = base.BuildContextMenu(/* ... */);
        /* etc. */
    }
    /* ... other custom logic ... */
}

I hope I didn't mess up the syntax, but that's the general idea.

Scott Whitlock
I'm afraid I don't understand it yet. Does this approach support adding plug-ins by adding (and registering?) just an assembly, or do I need recompilation of the main application for this? What do [Import...] and [Export...] do?
Serge van den Oever
All you would have to do to add plug-ins is drop more DLLs in the directory where your code is looking for plug-ins and it would find anything exporting this contract name (NodeTypes) of this type (INodeType). My answer does assume you have a basic introduction to MEF: http://www.codeplex.com/MEF
Scott Whitlock
In this case you would have to restart your code to have it see the new plugin, but there are examples on that site showing how to "re-compose" which will be able to find new plugins without restarting.
Scott Whitlock
Hi Scott, that was my problem:-) I heard of MEF, but had no knowledge of it so I didn't get it you were speaking in MEF terms! I'm going to dive into this. Thank you very much!
Serge van den Oever