MEF 导出导入 Expor Import
导出的
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Composition; namespace CalculatorContract { [Export(typeof(ICalculator))] public class Calculator : ICalculator { public IList<IOperation> GetOperations() { return new List<IOperation>() { new Operation { Name="+", NumberOperands=2}, new Operation { Name="-", NumberOperands=2}, new Operation { Name="/", NumberOperands=2}, new Operation { Name="*", NumberOperands=2} }; } public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": result = operands[0] + operands[1]; break; case "-": result = operands[0] - operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; default: throw new InvalidOperationException( String.Format("invalid operation {0}", operation.Name)); } return result; } } public class Operations2 { [Export("Add",typeof(Func<double,double,double>))] [ExportMetadata("speed","fast")] public double Add(double a, double b) { return a + b; } } public class Operations1 { [Export("Add", typeof(Func<double, double, double>))] [ExportMetadata("speed", "fast")] public double Add(double a, double b) { return a + b; } } }
导入的
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; namespace CalculatorContract { public class Program { [Import] public ICalculator Calculator { get; set; } /// <summary> /// 导入多个同名的方法 /// </summary> [ImportMany("Add",typeof(Func<double,double,double>))] public Lazy<Func<double, double, double>, IDictionary<string, object>>[] Addmethods { get; set; } static void Main(string[] args) { var p = new Program(); p.Run(); Console.ReadKey(); } public void Run() { var catalog = new DirectoryCatalog(@"C:\AddIns"); var container = new CompositionContainer(catalog); try { container.ComposeParts(this); Calculator.GetOperations(); foreach (var m in Addmethods) { Console.WriteLine( m.Value(1,2)); } } catch (ChangeRejectedException ex) { Console.WriteLine(ex.Message); return; } } } }
Expor导出 Import导入 dynamic也支持的
指定dll生成路径
copy "$(TargetPath)" "c:/addins"

浙公网安备 33010602011771号