MEF 初识

代码如下:

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Linq;
 4  using System.Text;
 5  using System.ComponentModel.Composition;
 6  using System.ComponentModel.Composition.Hosting;
 7 
 8  namespace meftest001
 9 {
10      class Program
11     {
12          static  void Main( string[] args)
13         {
14              var demo =  new DemoOne();
15             demo.Run( " 1 ");
16             Console.WriteLine( " ---- ");
17             demo.Run( " 2 ");
18             Console.ReadLine();
19         }
20     }
21 
22      ///   <summary>
23       ///  公用的 组装 处理
24       ///   </summary>
25       public  abstract  class BassClass
26     {
27          public BassClass()
28         {
29              var catalog =  new AggregateCatalog();
30             catalog.Catalogs.Add( new AssemblyCatalog( typeof(Program).Assembly));
31              var _container =  new CompositionContainer(catalog);
32             _container.ComposeParts( this);
33         }
34     }
35      public  interface DemoOneInterface
36     {
37          void Send( string msg);
38     }
39 
40      ///   <summary>
41       ///  导入
42       ///   </summary>
43       public  class DemoOne : BassClass
44     {
45         [ImportMany( " lyb ")]
46         IEnumerable<Lazy<DemoOneInterface, DemoOneInterfaceDepict>> DOlist;
47          public  void Run( string type)
48         {
49              foreach ( var _do  in DOlist.Where(item => item.Metadata.Depict == type))
50             {
51                 _do.Value.Send( " DemoOne.Send ");
52             }
53         }
54     }
55      ///   <summary>
56       ///  导出
57       ///   </summary>
58      [Export( " lyb "typeof(DemoOneInterface))]
59     [ExportMetadata( " Depict "" 1 ")]
60      public  class DemoOneInherit1 : DemoOneInterface
61     {
62          public  void Send( string msg)
63         {
64             Console.WriteLine( " DemoOneInherit1 send{0} ", msg);
65         }
66     }
67 
68      ///   <summary>
69       ///  导出
70       ///   </summary>
71      [Export( " lyb "typeof(DemoOneInterface))]
72     [ExportMetadata( " Depict "" 2 ")]
73      public  class DemoOneInherit2 : DemoOneInterface
74     {
75          public  void Send( string msg)
76         {
77             Console.WriteLine( " DemoOneInherit2 send{0} ", msg);
78         }
79     }
80      ///   <summary>
81       ///  定义 Metadata
82       ///   </summary>
83       public  interface DemoOneInterfaceDepict
84     {
85          string Depict {  get; }
86     }
87 }

 

转载于:https://www.cnblogs.com/lyb521569/p/4648877.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值