MEF的一个例子
MEF(Managed Extensibility Framework) .net framework4.0 加入,system.componentModel.composition
MEF与MAF(Managed Addin Framework)最大不同在于:前者关注使用非常简单的方式来支持具有很强灵活性的可扩展支持,后者关注具有物理隔离、安全、多版本支持的插件平台架构;
MEF和Unity不同在于:前者强调组合,后者强调依赖注入。
namespace Interfaces { public interface IPlugin { void Write(); } }
namespace OnePlugin { [Export(typeof(IPlugin))] public class OnePlugin:IPlugin { public void Write() { Console.WriteLine("one plugin"); } } }
namespace TwoPlugin { [Export(typeof(IPlugin))] public class TwoPlugin:IPlugin { public void Write() { Console.WriteLine("two plugin"); } } }
namespace MEFSample { class Program { static void Main(string[] args) { //使用反射的插件实现 //IEnumerable<Type> pluginTypes = GetPluginTypes(); //foreach (Type type in pluginTypes ) //{ // IPlugin plugin = (IPlugin)Activator.CreateInstance(type); // plugin.Write(); //} PluginProvider provider = new PluginProvider(); foreach (Lazy <IPlugin> plugin in provider .Plugins) { plugin.Value.Write(); } Console.Read(); } /// <summary> /// 使用反射的插件实现 /// </summary> /// <returns></returns> public static IEnumerable<Type> GetPluginTypes() { string root = AppDomain.CurrentDomain.BaseDirectory; string[] files = Directory.GetFiles(root,"*.dll", SearchOption.TopDirectoryOnly); List<Type> types = new List<Type>(); foreach (string file in files) { Type[] typearray = Assembly.LoadFrom(file).GetTypes(); foreach (Type type in typearray) types.Add(type); } return from type in types where type.IsClass && (typeof(IPlugin).IsAssignableFrom(type)) select type; //或者用yield return } } public class PluginProvider { [ImportMany] public IEnumerable<Lazy<IPlugin>> Plugins { get; private set; } //[Import] //public Lazy<IPlugin> PluginOne; public PluginProvider () { //var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(".")); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } }
还可以命名:
public interface ILogger { void WriteLog(string message); } [Export("TXT",typeof(ILogger))] public class TXTLogger : ILogger { public void WriteLog(string message) { System.Console.WriteLine(message); } } [Export("DB",typeof(ILogger))] public class DBLogger : ILogger { public void WriteLog(string message) { System.Console.WriteLine(message); } }
[Export] public class FacadeService { [Import("TXT")] public ILogger TXTLogger { get; set; } [Import("DB")] public ILogger DBLogger { get; set; } }
[Import] public FacadeService Service { get; set; }
public MainPage() { InitializeComponent(); var service = (Application.Current as App).Service; service.TXTLogger.WriteLog("写日志到文本文件"); service.DBLogger.WriteLog("写日志到数据库"); } 复制代码