Skip to content

Instantly share code, notes, and snippets.

@gogsbread
Created January 5, 2013 05:31
Show Gist options
  • Save gogsbread/4459941 to your computer and use it in GitHub Desktop.
Save gogsbread/4459941 to your computer and use it in GitHub Desktop.
Demonstrating MEF through the plight of Visual Studio extensions
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace RandomMusings
{
public interface IVSFeature
{
string Feature{get;}
}
public interface IVSAction
{
void Action();
}
[Export(typeof(IVSAction))]
[ExportMetadata("Feature","refactor")]
public class RefactorFeature:IVSAction
{
#region IVSFeature implementation
public void Action ()
{
Console.WriteLine("Code refactored");
}
#endregion
}
public class VisualStudioMEF
{
private CompositionContainer _featureContainer;
[ImportMany]
private IEnumerable<Lazy<IVSAction,IVSFeature>> _features;
public VisualStudioMEF ()
{
AssemblyCatalog _assemblyFeatures = new AssemblyCatalog(typeof(VisualStudioMEF).Assembly);
_featureContainer = new CompositionContainer(_assemblyFeatures);
try
{
//Fill in the imports for this object
_featureContainer.ComposeParts(this);
}
catch(CompositionException compositionException)
{
Console.WriteLine(compositionException.Message);
}
}
public bool PerformAction(string action)
{
foreach (Lazy<IVSAction,IVSFeature> feature in _features) {
if(feature.Metadata.Feature.Equals(action)){
feature.Value.Action();
return true;
}
}
return false;
}
}
public class Client
{
static void Main()
{
VisualStudioMEF vs = new VisualStudioMEF();
while(true)
{
Console.Write("What feature:");
string action = Console.ReadLine();
if(!vs.PerformAction(action))
{
Console.WriteLine("Feature not found");
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment