MEF Managed Extensibility Framework
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MEFDemo { class Program { private CompositionContainer _container; [Import(typeof(ICalculator))] public ICalculator calculator; [Export(typeof(ICalculator))] class MySimpleCalculator : ICalculator { [ImportMany] IEnumerable<Lazy<IOperation, IOperationData>> operations; public string Calculate(string input) { int left; int right; Char operation; int fn = FindFirstNonDigit(input); //finds the operator if (fn < 0) return "Could not parse command."; try { //separate out the operands left = int.Parse(input.Substring(0, fn)); right = int.Parse(input.Substring(fn + 1)); } catch { return "Could not parse command."; } operation = input[fn]; foreach (Lazy<IOperation, IOperationData> i in operations) { if (i.Metadata.Symbol.Equals(operation)) return i.Value.Operate(left, right).ToString(); } return "Operation Not Found!"; } private int FindFirstNonDigit(String s) { for (int i = 0; i < s.Length; i++) { if (!(Char.IsDigit(s[i]))) return i; } return -1; } } public Program() { var _catalog = new AggregateCatalog(); _catalog.Catalogs.Add(new AssemblyCatalog(typeof (Program).Assembly)); _container=new CompositionContainer(_catalog); //Fill the imports of this object try { this._container.ComposeParts(this); } catch (CompositionException compositionException) { Console.WriteLine(compositionException.ToString()); } } static void Main(string[] args) { Program p = new Program(); //Composition is performed in the constructor String s; Console.WriteLine("Enter Command:"); while (true) { s = Console.ReadLine(); Console.WriteLine(p.calculator.Calculate(s)); } } } [Export(typeof(IOperation))] [ExportMetadata("Symbol", '+')] class Add : IOperation { public int Operate(int left, int right) { return left + right; } } [Export(typeof(IOperation))] [ExportMetadata("Symbol", '-')] class Subtract : IOperation { public int Operate(int left, int right) { return left - right; } } public interface ICalculator { String Calculate(String input); } public interface IOperation { int Operate(int left, int right); } public interface IOperationData { Char Symbol { get; } } }
http://msdn.microsoft.com/zh-cn/library/vstudio/dd460648.aspx