MEF初步

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
//以下三个命名空间必须
using System.Reflection;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace ConsoleApplication1
{
    class Program
    {
        //主程序
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
        }

        public void Run()
        {
            Compend c = new Compend();
            foreach (var item in c.iPersons)
            {
                item.Write();
            }
            Console.ReadKey();
        }
    }

    //申明导入
    public class Compend
    {
        [ImportMany]//标识为导入,当要导入多个时用ImportMany,一个是为Import
        public IEnumerable<IPerson> iPersons { get; set; }//还可为 IPerson[]
        public Compend()
        {
            //把从指定path发现的部件添加到目录中。此处表示就在当前程序中
            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            //AggregateCatalog aggregate = new AggregateCatalog();
            //aggregate.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            //aggregate.Catalogs.Add(new DirectoryCatalog(Directory.GetCurrentDirectory()));
            //AssemblyCatalog catalog = new AssemblyCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath);
            //定义组合容器
            CompositionContainer container = new CompositionContainer(aggregate);
            //通过调用容器的ComposeParts()方法可以把容器中的部件组合到一起
            container.ComposeParts(this);//this
        }
    }

    [Export]//声明导出
    public class PersonE:IPerson
    {

        public void Write()
        {
            Console.WriteLine("EEEEEEE");
        }
    }

    //声明为导出,并指定导入类型为IPerson,这样,方便导入类型标识为IPerson的导入部件的发现,就可以从此处导入
    [Export(typeof(IPerson))]
    public class PersonC : IPerson
    {
        public void Write()
        {
            Console.WriteLine("CCCCCCCCCCCC");
        }
    }

    public interface IPerson//接口
    {
        void Write();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值