MEF学习笔记

来源:互联网 发布:塑料水晶高跟鞋淘宝 编辑:程序博客网 时间:2024/04/27 02:04

MEF学习笔记

一.来点废话

 在学习PRISM时遇到了MEF和Unity,然后就在网络上翻看大师们的案例,但是我还是觉得我自己要敲一边比较好。 [MEF官方解释](https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx)

二.代码和截图

  • 整个解决方案结构

项目截图

  • IMEFLibary.Send代码
    很简单,就定义一个接口;

public interface ISend
{
void DoSend(string str);
}

  • CMFELibary.CSendA代码
    同样很简单,就是实现ISend

namespace CMEFLibrary
{
[Export(typeof(IMEFLibary.ISend))]
public class CSendA:ISend
{
public void DoSend(string str)
{
Console.WriteLine(“C”+str);
}
}
}

  • 控制台程序 Demo2

using IMEFLibary;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MEFDemo2
{
class Program
{
[Import]
public ISend Send { get; set; }
static void Main(string[] args)
{

        Program pro = new Program();        pro.Compose();        if (pro.Send != null)        {            pro.Send.DoSend("Ha Ha MEF");        }        Console.Read();    }    private void Compose()    {        //var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());        var catalog = new AssemblyCatalog(Assembly.LoadFile(System.Environment.CurrentDirectory+"\\"+ "CMEFLibrary"+".dll"));        CompositionContainer container = new CompositionContainer(catalog);        container.ComposeParts(this);    }}

}

  • 将CMFELibary编译的Dll放置到Demo2的Debug文件夹下面
    这里写图片描述
    -编译,大功告成!

这里写图片描述