一、演示概述
此演示初步介绍了MEF的基本使用,包括对MEF中的Export、Import和Catalog做了初步的介绍,并通过一个具体的Demo来展示MEF是如何实现高内聚、低耦合和高扩展性的软件架构。namespace Interface
{
public interface IBookService
{
void GetBookName();
}
}using System;
using System.ComponentModel.Composition;
using Interface;
namespace ComputerBookServiceImp
{
[Export(typeof(IBookService))]
public class ComputerBookService : IBookService
{
public void GetBookName()
{
Console.WriteLine("Computer Book");
}
}
}using System;
using System.ComponentModel.Composition;
using Interface;
namespace HistoryBookServiceImp
{
[Export(typeof(IBookService))]
public class HistoryBookService : IBookService
{
public void GetBookName()
{
Console.WriteLine("History Book");
}
}
}using System;
using System.ComponentModel.Composition;
using Interface;
namespace MathBookServiceImp
{
[Export(typeof(IBookService))]
public class MathBookService : IBookService
{
public void GetBookName()
{
Console.WriteLine("Math Book");
}
}
}using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using Interface;
namespace HostApp
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.Compose();
program.BookService.GetBookName();
}
[Import]
public IBookService BookService { get; set; }
/// <summary>
/// 通过容器对象将宿主和部件组装到一起。
/// </summary>
public void Compose()
{
DirectoryCatalog directoryCatalog = new DirectoryCatalog("imps");
var container = new CompositionContainer(directoryCatalog);
container.ComposeParts(this);
}
}
}原文:http://blog.csdn.net/gjysk/article/details/44648505