下面我们来主要讲解一下MEF中的导入和导出,还是上一篇的代码(这篇中,我还会贴出完整的代码),修改Program的代码如下:
using System;
using System.Collections.Generic;
using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; namespace MEFDemo { class Program { [Import("MusicBook")] public IBookService Service { get; set; } static void Main(string[] args) { Program pro = new Program(); pro.Compose(); if (pro.Service != null) { Console.WriteLine(pro.Service.GetBookName()); } Console.Read(); } private void Compose() { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(this); } } }
修改MusicBook的代码如下:
using System;
using System.Collections.Generic;
using System.Linq; using System.Text; using System.ComponentModel.Composition; namespace MEFDemo { [Export("MusicBook",typeof(IBookService))] public class MusicBook : IBookService { public string BookName { get; set; } public string GetBookName() { return "MusicBook"; } } }</