zoukankan      html  css  js  c++  java
  • MEF初体验之一:在应用程序宿主MEF

    在MEF出现以前,其实微软已经发布了一个类似的框架,叫MAF(Managed Add-in Framework),它旨在使应用程序孤立和更好的管理扩展,而MEF更关心的是可发现性、扩展性和轻便性,后者更lightweight。我们将跟随MEF官网来学习。

    The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.

    1.How to host MEF

    First,add reference to System.ComponentModel.Composition assembly,then instantiate CompositionContainer,add some composable parts you want and hosting application to the container,in the end compose them.

    2.An simple example

    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 HostingMef
    {
        class Program
        {
            [Import]
            public IMessageSender MessageSender { get; set; }
            static void Main(string[] args)
            {
                Program p = new Program();
                p.Composite();
                p.MessageSender.Send("Message Sent");
                Console.ReadKey();
            }
            void Composite()
            { 
                var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
                var container = new CompositionContainer(catalog);
                container.ComposeParts(this, new EmailSender());
            }
        }
        interface IMessageSender
        {
            void Send(string msg);
        }
        [Export(typeof(IMessageSender))]
        class EmailSender : IMessageSender
        {
            public void Send(string msg)
            {
                Console.WriteLine(msg);
            }
        }
    
    }
    View Code

    结果正如预期:

    在MEF组合模型中,CompositionContainer是核心,它包含了一些可用的Parts并且组合它们,也就是说使宿主程序中的Imports能匹配到Exports。而CompositionContainer是怎么发现哪些parts是available的呢?答案是它通过Catalogs,Catalogs通过提供的type、assembly或者directory来发现来自不同源的parts.在上面的例子中,通过使用Export特性和Import特性来实现了DI,避免了MessageSender在编译时对EmailSender的依赖。当然,这里只使用了一个Export特性和一个Import特性,并不一直这样,在后面我们将看到多个的情况。

  • 相关阅读:
    Linux oracle操作
    Job
    Oracle创建表空间和用户并分配权限
    Oracle赋予用户查询另一个用户所有表的权限
    plsql中文乱码解决方案
    PLSQL创建Oracle定时任务,定时执行存储过程
    fcntl函数参数F_GETPIPE_SZ、F_SETPIPE_SZ报错引出的关于linux-specific头文件的使用方法
    从Windows Server 2008 迁移mantis到CentOS 6.8
    从Windows Server 2008 迁移VisualSVN到CentOS 6.8
    CentOS 6.8上开启NFS服务给不同用户使用的曲线设置方法
  • 原文地址:https://www.cnblogs.com/jellochen/p/3660282.html
Copyright © 2011-2022 走看看