zoukankan      html  css  js  c++  java
  • 原来写插件还可以选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

  • 相关阅读:
    初识python 2.x与3.x 区别
    装饰器
    函数的进阶
    Spring Boot启动问题:Cannot determine embedded database driver class for database type NONE
    22.Spring Cloud Config安全保护
    23.Spring Cloud Bus 无法更新问题(踩坑) Spring cloud config server Could not fetch remote for master remote
    24.Spring Cloud之Spring Cloud Config及Spring Cloud Bus
    Spring Boot整合Spring Data Elasticsearch 踩坑
    项目中Spring Security 整合Spring Session实现记住我功能
    32.再谈SpringBoot文件上传
  • 原文地址:https://www.cnblogs.com/stjwy/p/5986591.html
Copyright © 2011-2022 走看看