接上一篇:推荐使用MEF降低耦合
本章主旨:在上一篇基础上新增 1)如何通过添加标记,区分插件类实现接口 2)优化设计AggregateCatalog的加载
1)如何通过添加标记,
1 /// <summary> 2 /// 插件类1 实现接口 3 /// </summary> 4 [Export(typeof(DemoOneInterface))] 5 public class DemoOneInherit1 : DemoOneInterface 6 { 7 public string GetName() 8 { 9 return "DemoOneInherit1"; 10 } 11 }
1 /// <summary> 2 /// 插件类2 实现接口 3 /// </summary> 4 [Export(typeof(DemoOneInterface))] 5 public class DemoOneInherit2 : DemoOneInterface 6 { 7 public string GetName() 8 { 9 return "DemoOneInherit2"; 10 } 11 }
现在的问题是:如果能区分以下 “插件类2 实现接口” 和“ 插件类2 实现接口”那就好了,为了解决这个问题,引入ExportMetadata来为插件的特殊属性进行标记。
新增插件标记接口
1 public interface DemoOneInterfaceDepict 2 { 3 string Depict{get;} 4 }
添加 :为插件定义描述
1 /// <summary> 2 /// 插件类1 实现接口 3 /// </summary> 4 [Export(typeof(DemoOneInterface))] 5 //为插件定义描述 6 [ExportMetadata("Depict", "插件类1")] 7 public class DemoOneInherit1 : DemoOneInterface 8 { 9 public string GetName() 10 { 11 return "DemoOneInherit1"; 12 } 13 }
1 /// <summary> 2 /// 插件类2 实现接口 3 /// </summary> 4 [Export(typeof(DemoOneInterface))] 5 //为插件定义描述 6 [ExportMetadata("Depict", "插件类2")] 7 public class DemoOneInherit2 : DemoOneInterface 8 { 9 public string GetName() 10 { 11 return "DemoOneInherit2"; 12 } 13 }
修改代码:新增标记接口DemoOneInterfaceDepict,并且引入Lazy延迟加载,获取标记信息
[ImportMany]
IEnumerable<Lazy<DemoOneInterface, DemoOneInterfaceDepict>> DoList;
1 string Inherit = System.Configuration.ConfigurationSettings.AppSettings["Inherit"]; 2 string name = ""; 3 foreach (var _do in DoList.Where(e=>e.Metadata.Depict==Inherit)) 4 { 5 name = _do.Value.GetName(); 6 }
2)优化设计AggregateCatalog的加载,不用每次都写一次,
1 var catalog = new AggregateCatalog(); 2 catalog.Catalogs.Add(new AssemblyCatalog(typeof(T).Assembly)); 3 catalog.Catalogs.Add(new DirectoryCatalog(path)); 4 var _container = new CompositionContainer(catalog); 5 _container.ComposeParts(obj); 6 return obj;
新增 静态抽象类 public static class ObjectExtBase 因为c#不可以同时继承多个类,因此做成扩展方法
1 /// <summary> 2 /// 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="obj"></param> 6 /// <param name="path">引入的路径</param> 7 /// <returns></returns> 8 public static T ComposePartsSelf<T>(this T obj,string path) where T : class 9 { 10 var catalog = new AggregateCatalog(); 11 catalog.Catalogs.Add(new AssemblyCatalog(typeof(T).Assembly)); 12 catalog.Catalogs.Add(new DirectoryCatalog(path)); 13 var _container = new CompositionContainer(catalog); 14 _container.ComposeParts(obj); 15 return obj; 16 }
在引入的时候,只需要调用 this.ComposePartsSelf(path);即可
1 static void Main(string[] args) 2 { 3 var demo = new DemoOne(@"H:\开发资料\WinFormsAppMEF\ConsoleApplication1\Addin");//遍历运行目录下的Addin文件夹,查找所需的插件。 4 Console.WriteLine(demo.Run()); 5 Console.ReadLine(); 6 }
时间: 2024-10-08 11:13:07