Created
November 11, 2012 09:34
-
-
Save maximilian-krauss/4054299 to your computer and use it in GitHub Desktop.
MEF Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.Composition; | |
using System.ComponentModel.Composition.Hosting; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
namespace ConsoleApplication1 { | |
class Program { | |
static void Main(string[] args) { | |
var p = new PluginManager(); | |
p.LoadPlugins(); | |
foreach (var plugin in p.Plugins) | |
Console.WriteLine(string.Format("{0}: {1}", plugin.Name, plugin.DoSomething("This is a test."))); | |
Console.ReadLine(); | |
} | |
} | |
public class PluginManager { | |
[ImportMany(typeof(IPlugin))] | |
public List<IPlugin> Plugins { get; set; } | |
public void LoadPlugins() { | |
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); | |
var container = new CompositionContainer(catalog); | |
container.ComposeParts(this); | |
} | |
} | |
public interface IPlugin { | |
string Name { get; } | |
string DoSomething(string input); | |
} | |
[Export(typeof(IPlugin))] | |
public class PluginA:IPlugin { | |
public string Name { get { return "Plugin A"; } } | |
public string DoSomething(string input) { | |
return input.ToUpperInvariant(); | |
} | |
} | |
[Export(typeof(IPlugin))] | |
public class PluginB:IPlugin { | |
public string Name { get { return "Plugin B"; } } | |
public string DoSomething(string input) { | |
return string.Format(">>>>{0}<<<<", input); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment