上一篇我們已經可以獲取各種FileHandler的實例和對應的元數據。本篇,我們做一個稍微完整的文件管理器。
1、修改接口IFileHandler,傳入文件名
namespace IPart
{
public interface IFileHandler
{
void Process(string fileName);
}
}
2、修改具體的FileHandler。
using IPart;
using System;
using System.ComponentModel.Composition;
namespace Parts
{
[Export(typeof(IFileHandler))]//表示此類需要導出,導出的類型為IFileHandler
[ExportMetadata("Extension", ".txt")]//添加導出元數據Extension,值為.txt
public class TxtFileHandler : IFileHandler
{
public void Process(string fileName)
{
Console.WriteLine("處理文本文件"+fileName);
}
}
}
3、修改主函數
using IPart;
using System;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
namespace meftest
{
class Program
{
//容器,裝東西用的。具體裝什麼先不管。
private static CompositionContainer container;
static void Main(string[] args)
{
//模擬數據。
string[] files = new string[] {
@"c:\xxoo\xxoo.txt",
@"c:\xxoo\ooxx.doc",
@"d:\測試目錄\mm.jpg",
@"e:\電影\天海翼.avi",
};
//AssemblyCatalog 目錄的一種,表示在程序集中搜索
var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);//此處這一句實際上沒啥用,因為此程序集下沒有任何我們需要的實例(各種handler)
//在某個目錄下的dll中搜索。
var directoryCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory,"*.dll");
var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);
//創建搜索到的部件,放到容器中。
container = new CompositionContainer(aggregateCatalog);
var exports = container.GetExports<IFileHandler,IPatMetadata>();//獲得所有導出的部件(IFileHandler,並且帶有IPatMetadata類型元數據,並且元數據的名字為Extension的實例)。
foreach (var file in files)
{
string ext = System.IO.Path.GetExtension(file).ToLower();
var export = exports.SingleOrDefault(o => o.Metadata.Extension == ext);//根據擴展名,也就是元數據來找到對應的處理實例,如果你找到了多個,會thow一個錯誤。
if (export != null)
export.Value.Process(file);
}
Console.ReadLine();
}
}
}
運行結果:

可以看到,對每一個具體的文件,均找到了正確的處理實例進行處理。avi文件,沒有找到處理的實例,就沒處理。
擴展:
現在要能處理avi,非常的簡單,隨便拷貝一個Handler,實現Avi文件的處理邏輯即可,當然你仍然需要拷貝dll。
using IPart;
using System;
using System.ComponentModel.Composition;
namespace Parts
{
[Export(typeof(IFileHandler))]//表示此類需要導出,導出的類型為IFileHandler
[ExportMetadata("Extension", ".avi")]//添加導出元數據Extension,值為.txt
public class AviFileHandler : IFileHandler
{
public void Process(string fileName)
{
Console.WriteLine("播放av文件"+fileName);
}
}
}

你看,擴展是不是很簡單,只需要實現處理邏輯,主程序就可以多處理一種文件類型了。接口和主程序根本就不需要做改動。
和其他IOC框架相比,MEF不需要配置文件,用attribute的方式來做配置,非常的清楚簡潔。
總結:
你用了十分鐘就能看完這個系列,把所有項目都建一遍跑完,也就花個把小時。現在,你得到了一個新技能MEF,而且達到了我的水平,哈哈。
本人很菜,學MEF,園子裡的文章好像對我來說有點難,走了一些彎路,最終才搞明白一些。因此想寫一個能講簡單清楚一點的入門教程,也不知道目標達到了沒有。
告訴我,MEF,你入門了沒有。
最恨天下文章一大抄,請不要轉載。