MEF入门之不求甚解,但力求简单能讲明白(五)

我们已经成功的达到了目标,大量减少了if else。

不过在园子里面的文章大多,用的是Import、ImportMany。So,修改主函数。

using IPart;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;

namespace meftest
{
    class Program
    {
        [ImportMany]
        private IEnumerable<Lazy<IFileHandler, IPatMetadata>> fileHandlers;//警告,说没有赋值过。不用理会,MEF会自己导入的。
        static void Main(string[] args)
        {
            //模拟数据。
            string[] files = new string[] {
                @"c:xxooxxoo.txt",
                @"c:xxooooxx.doc",
                @"d:测试目录mm.jpg",
                @"e:电影天海翼.avi",
            };
            Program p = new Program();
            p.Compose();
            foreach (var file in files)
            {
                string ext = System.IO.Path.GetExtension(file).ToLower();
                var export = p.fileHandlers.SingleOrDefault(o => o.Metadata.Extension == ext);//根据扩展名,也就是元数据来找到对应的处理实例
                if (export != null)
                    export.Value.Process(file);
            }
            Console.ReadLine();
        }
        private void Compose()
        {
            //AssemblyCatalog 目录的一种,表示在程序集中搜索
            var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);//此处这一句实际上没啥用,因为此程序集下没有任何我们需要的实例(各种handler)
            //在某个目录下的dll中搜索。
            var directoryCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
            var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);//聚合目录包含有2种搜索方式
            var container = new CompositionContainer(aggregateCatalog);
            container.ComposeParts(this);//将部件组合在一起。意思就是将所有Export的部件,装配到this实例中标记为Import、ImportMany的属性上。
        }
    }
}

不过这里有一个要注意的地方,不能在主函数内部来进行装配。原因如下图。

运行结果:

ok,现在MEF你已经入门了,再看大神们的文章心里也有点底了。本系列到此结束。

原文地址:https://www.cnblogs.com/luhuanong/p/5541581.html