您的位置:首页 > 编程语言 > C#

MEF初步使用

2016-02-17 00:00 597 查看
摘要: MEF初步使用

MEF(Managed Extensibility Framework)是一个用于创建可扩展的轻型应用程序的库。 应用程序开发人员可利用该库发现并使用扩展,而无需进行配置。 扩展开发人员还可以利用该库轻松地封装代码,避免生成脆弱的硬依赖项。 通过 MEF,不仅可以在应用程序内重用扩展,还可以在应用程序之间重用扩展。(摘自MSDN)

我初步使用后的感受是通过这个应用程序库,我们可以实现接口功能的扩展和自动导入到实例,不需要自己编码对接口进行实现。它可以在指定的程序集中搜索匹配合适的接口实现,然后导入使用。

弄了一个控制台程序,代码不多,很简单,我就直接上代码了。看完了应该会有一个初步认知。

文件一:program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MEFdemo
{
class Program
{

public IbookService book { get; set; }
public IFoodService Food { get; set; }
public CompositionContainer container { get; set; }
static void Main(string[] args)
{
Program pro = new Program();
pro.Compose();
pro.book = pro.container.GetExportedValueOrDefault<IbookService>("musicbook");
Console.WriteLine(pro.book.GetBookName());
pro.book = pro.container.GetExportedValueOrDefault<IbookService>("historybook");
Console.WriteLine(pro.book.GetBookName());
pro.Food = pro.container.GetExportedValueOrDefault<IFoodService>("musicbook");
if (pro.Food == null)
pro.Food = pro.container.GetExportedValue<IFoodService>();//GetExportedValue与GetExportedValueOrDefault的区别
// 在于后者找不到匹配度的,会异常报错
Console.WriteLine(pro.Food.GetFoodName());
Console.WriteLine("当前程序集路径:" + Assembly.GetExecutingAssembly().Location);
Console.Read();
}
/// <summary>
/// 构造好组合容器
/// </summary>
private void Compose()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());//指定程序集目录
container = new CompositionContainer(catalog);//设定部件容器为该目录下
}

}
}

文件二:initalInterFace.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MEFdemo
{
public interface IbookService
{
string BookName { get; set; }
string GetBookName();
}
public interface IFoodService
{
string FoodName { get; set; }
string GetFoodName();
}
[Export("musicbook", typeof(IbookService))]
public class MusicBook : IbookService
{
public string BookName { get; set; }
public string GetBookName()
{
return "MusicBook";
}
}
[Export("historybook", typeof(IbookService))]
public class HistoryBook : IbookService
{
public string BookName { get; set; }
public string GetBookName()
{
return "HistoryBook";
}
}
[Export("musicbook", typeof(IFoodService))]
public class apple:IFoodService{
public string FoodName { get; set; }
public string GetFoodName()
{
return "苹果";
}
}
}

其实上面的代码,展示了如何使用Export导出实现后的接口,已经取相同名字不同接口,不同名字相同接口的实现情况。

有兴趣的可以耐心看看。

运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# MEF