• 原来写插件还可以选MEF


    MEF是微软提供的一个轻量级的ICO容器,可以轻易的解除程序集的依赖关系,最近想写个类似插件试的软件所以搜索了一下,终于淘到宝了。

    下面我们看看MEF是如何解耦的

    新建一个控制台项目两个类库

     

    Itest中添加接口文件Istudent

    namespace ITest

    {

        public interface   IStudent

        {

             string Say(string msg);

        }

    }

    Test中添加引用

     

    添加Student类文件;

    using ITest;

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.ComponentModel.Composition;//添加引用

    namespace Test

    {

         [Export(typeof(IStudent))]//用于输出类行

        public class Student:IStudent

        {

            public string Say(string msg)

            {

                return "你好:" + msg;

            }

        }

    }

    控制台程序中也添加引用

    注意只添加了接口类库的引用,并没有添加Test类库的引用;

     

    编写主函数:

    using ITest;

    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.IO;

     

    namespace MEF

    {

        class Program

        {

            [Import]//MEF导入特性标签,用于实例化;

            public IStudent student { get; set; }

            static void Main(string[] args)

            {

                Program p = new Program();

                p.Deal();

            }

     

            public void Deal()

            {

                AggregateCatalog catelog = new AggregateCatalog();

     

                catelog.Catalogs.Add(new DirectoryCatalog("..\..\..\Test\bin\Debug"));//根据相对路径去找对象;

     

                CompositionContainer container = new CompositionContainer(catelog);//声明容器

     

                container.ComposeParts(this);//把容器中的部件组合到一起

     

                Console.WriteLine(student.Say("干嘛去?"));

                Console.Read();

            }

        }

    }

     

     

     

    总结:

    MEF自动将  [Export(typeof(IStudent))]和[Import]指定的两个对象进行绑定,帮助我们完成实例化;

    MEF实例化对象只需要四部,

    1. 创建合并对象目录AggregateCatalog实例
    2. 根据地址添加目录到对象中;
    3. 创建容器对象,
    4. 绑定导入和导出的对象,完成实例化;

    参考文档:

    http://www.cnblogs.com/techborther/archive/2012/02/06/2339877.html

  • 相关阅读:
    标识符
    Bootstrap笔记——Checkbox选项组
    servlet实现简单验证码
    javascript笔记——登录表单验证
    JSP的隐式对象(page,config,pageContext,exception)
    创建Servlet文件不自动生成web.xml原因
    JSP的隐式对象(application)
    前端开发工具——brackets的使用
    《Shell脚本学习 —— Shell变量、字符串、数组、注释》
    《开发板 — 3399pro备份整个文件系统》
  • 原文地址:https://www.cnblogs.com/stjwy/p/5986591.html
Copyright © 2020-2023  润新知