`

How-to:应用mef 提高程序扩展能力(part2)

阅读更多

More Value of MEF

一、catalog基本使用

Ok, I think we can all agree that we added a little complexity if all we were going to do is factor what was in the same assembly. MEF really shines when you have separate independent groups working on different components.  By definition these are often in different assemblies with cross no dependencies.  To show how MEF supports this, let's add a new Class Library project to our solution.    Call it ExternalMessages and add a reference to the System.ComponentModel.Composition.dll assembly.

 

STEP 1:

Add the following class.

   1: using System;
   2: using System.ComponentModel.Composition;
   3:  
   4: public class Class1
   5: {
   6:     [Export]
   7:     public string Message
   8:     {
   9:         get
  10:         {
  11:             return "I am starting to get it...";
  12:         }
  13:     }
  14: }

 

STEP 2:

Now we need to wire up this class into the catalog...    Notice in line 6, we change the catalog to look in a directory for the parts... 

 

   1: public void Run()
   2:  {
   3:      //SimpleHello hello = new SimpleHello();
   4:      //Message = hello.Message;
   5:      var catalog = new DirectoryPartCatalog(@"..\..\..\ExternalMessages\bin\Debug");
   6:          // new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
   7:      var container = new CompositionContainer(catalog.CreateResolver());
   8:      container.AddPart(this);
   9:      container.Compose();
  10:  
  11:      foreach (var s in Messages)
  12:      {
  13:          Console.WriteLine(s);
  14:      }
  15:  
  16:  
  17:      Console.ReadKey();
  18:  }

Note: DirectoryPartCatalog also supports relative paths that will look for a path under the current AppDomain.CurrentDomain.BaseDirectory.  For example:
new DirectoryPartCatalog(@”.\extensions\”);

Run it and we get our new message! 

 

STEP 3:

Cool, but we lost our old messages, and I kind of liked them too...  Well, luckily, we have an aggregate part catalog that can take parts from several sources.

   1: public void Run()
   2:  {
   3:      //SimpleHello hello = new SimpleHello();
   4:      //Message = hello.Message;
   5:      var catalog = new AggregatingComposablePartCatalog();
   6:         catalog.Catalogs.Add (new DirectoryPartCatalog(@"..\..\..\ExternalMessages\bin\Debug"));
   7:         catalog.Catalogs.Add (new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
   8:      var container = new CompositionContainer(catalog.CreateResolver());
   9:      container.AddPart(this);
  10:      container.Compose();

Pretty cool, we now get all the messages!

 

输出为:

I am starting to get it ...

hello world!!

This is getting fun!

 

STEP 4:

Finally, just to bring up the point here... I created a bunch of different assemblies that exported Messages... All I need to do is point the catalog at them and go. 



 

   1: public void Run()
   2: {
   3:     //SimpleHello hello = new SimpleHello();
   4:     //Message = hello.Message;
   5:     var catalog = new AggregatingComposablePartCatalog();
   6:        catalog.Catalogs.Add (new DirectoryPartCatalog(@"..\..\..\ExternalMessages\bin\Debug"));
   7:        catalog.Catalogs.Add(new DirectoryPartCatalog(@"..\..\..\ExtraMessages"));
   8:        catalog.Catalogs.Add (new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
   9:     var container = new CompositionContainer(catalog.CreateResolver());
  10:     container.AddPart(this);
  11:     container.Compose();
  12:  

See where I added them in line 7..    Now just copy the assemblies into this directory and they become available for this program to use! Notice how I don't need to change any of the logic of the core program as I add more and more extensions. 

 

输出看下图:



 

Taking MEF to the Next Level

Above I showed the simplest scenario... let's get a bit more powerful.  If you pick apart the main program looking for tight coupling, that Console.WriteLine() will really stand out.. What if you want to log to a file, call a web service or print to HTML or WPF?   Tightly coupling to the Console does not make that easy.  How can we use the seperation of concerns principle and MEF to get rid of this tight coupling? 

 

二、进行一点点扩展

STEP 1:

First, we need to define an interface that describes the contract for outputting strings.  To ensure correct dependency management go ahead and create a new Library project called SharedLibrary, add this interface and reference this project from each of the other team projects. 

   1: namespace SharedLibrary
   2: {
   3:     public interface IOutputString
   4:     {
   5:         void OutputStringToConsole(string value);
   6:     }
   7: }

 

STEP 2:

Now, back in the main program we can factor out the Console.WriteLine ()...

   1: class Program
   2: {
   3:     [Import]
   4:     public IEnumerable<string> Messages { get; set; }
   5:  
   6:     [Import]
   7:     public IOutputString Out { get; set; }
   8:  
   9:     public void Run()
  10:     {
  11:         //SimpleHello hello = new SimpleHello();
  12:         //Message = hello.Message;
  13:         var catalog = new AggregatingComposablePartCatalog();
  14:            catalog.Catalogs.Add (new DirectoryPartCatalog(@"..\..\..\ExternalMessages\bin\Debug"));
  15:            catalog.Catalogs.Add(new DirectoryPartCatalog(@"..\..\..\ExtraMessages"));
  16:            catalog.Catalogs.Add (new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
  17:         var container = new CompositionContainer(catalog.CreateResolver());
  18:         container.AddPart(this);
  19:         container.Compose();
  20:  
  21:         foreach (var s in Messages)
  22:         {
  23:             Out.OutputString(s);
  24:         }
  25:  
  26:     
  27:         Console.ReadKey();
  28:     }

In line 6-7 we define Out and in line 23 we change from Console.WriteLine() to Out.OutputString().

 

STEP 3:

Now in External Messages project add the following class

   1: [Export(typeof(IOutputString))]
   2: public class Class1 : IOutputString
   3: {
   4:     public void OutputString(string value)
   5:     {
   6:         Console.WriteLine("Output=" + value);
   7:     }
   8:  
   9:     

 

Notice here we are explicitly saying the expert type to be that shared interface.  Now when we run it we get:



 

  • 大小: 129.1 KB
  • 大小: 73.5 KB
  • 大小: 63.2 KB
分享到:
评论

相关推荐

    MEF框架源代码 MEF框架源代码 MEF框架源代码

    6. **部分类(Part)**:在MEF中,组件通常被称为“部分”,因为它们可以是整个应用程序的一部分,每个部分都可能独立地被替换或扩展。 7. **目录(Catalog)**:目录是包含组件定义的集合,它可以是基于文件系统、...

    MEF-based-WCF-Services:MEF的例子

    总之,MEF-based WCF Services允许我们构建灵活、可扩展的服务,利用C#的特性实现组件之间的依赖注入,使服务能够在运行时动态适应变化。通过深入学习和实践,你可以创建更加健壮和适应性强的WCF解决方案。

    MEF 2 _Preview2

    2. MEF-Silverlight-v40.sln:这表明MEF 2也支持Silverlight平台,这是一个已弃用的轻量级Web应用程序框架。这个解决方案文件可能包含专门针对Silverlight环境的MEF实现。 3. dumbkey.snk:这是一个强名称密钥文件,...

    MEF 注入框架入门导引 ppt

    - **MEF(Managed Extensibility Framework)**:是.NET Framework中的一个新库,旨在提高应用程序和组件的重用能力。通过使用MEF,.NET应用能够从静态编译转变为动态组合。 - **软件开发与维护的挑战**: - 原始...

    mef04g-bak-r-iz:mef04g-bak-r-iz 由 GitHub Classroom 创建

    【标题】"mef04g-bak-r-iz: GitHub Classroom 创建的 mef04g-bak-r-iz 项目备份" 这个标题表明我们正在讨论一个由 GitHub Classroom 创建的项目,项目名为 "mef04g-bak-r-iz"。GitHub Classroom 是一个平台,教师...

    vs-mef:Visual Studio使用的托管扩展框架(MEF)实现

    VS MEF(Visual Studio的托管可扩展性框架风格) 特征 您现有的MEF零件的新的,更快的主机 重用您已经在使用的MEF属性 ExportFactory支持创建具有范围有效期(即共享边界)的子容器 文献资料

    mef与wcf整合

    MEF(Managed Extensibility Framework)是.NET Framework中一个用于构建可扩展应用程序的库,它允许开发者在运行时发现并使用外部组件,实现了插件式架构。而WCF(Windows Communication Foundation)是微软提供的...

    MEF-报告:数字时代的个人隐私和对品牌的长期信任(英文)-2020.8-11页2020精品报告.pdf

    他们可能会删除应用程序,或者甚至根本不下载它们。如果他们认为自己的个人信息不安全,他们会取消购买或交易。如果他们感觉组织可能会滥用他们的信任或数据,他们将选择不与该企业合作。 这份报告为行业领导者提供...

    引导程序:MEF Autofac应用程序引导程序

    MEF(Managed Extensibility Framework)是微软提供的一个开源库,它允许开发者创建可扩展的应用程序。MEF通过发现和组合应用中的组件来实现这一目标,这些组件可以是在运行时动态加载的。MEF的核心概念包括导入...

    WPF prism MEF 架构

    - **插件架构(Plugin Architecture)**:MEF提供了一种机制,允许应用程序在运行时发现和加载外部组件,这些组件可以在不修改主应用程序的情况下添加新功能或扩展已有功能。 - **导出(Export)和导入(Import)**...

    MEF 结合 MVVMLight

    MEF是一个用于构建可扩展应用程序的.NET框架,而MVVMLight则是一个轻量级的MVVM(Model-View-ViewModel)设计模式实现库,它简化了UI和业务逻辑之间的解耦。** **MEF的主要功能包括:** 1. **组件发现**:MEF允许...

    MEF 10.2.pdf

    MEF 10.2文档是关于metro ethernet技术的权威标准,名为“Technical Specification MEF 10.2 Ethernet Services Attributes Phase 2”,该文档于2009年10月27日发布。MEF,即Metro Ethernet Forum(城域以太网论坛)...

    MEF简单应用

    MEF的主要目标是简化软件的可插拔性和模块化,允许开发者轻松地引入第三方组件或扩展现有功能,而无需深入修改应用程序的核心代码。在本篇中,我们将探讨MEF的基本概念、如何导入和导出部件,以及如何在控制台应用...

    WPF中MEF的应用,简单实例

    总之,MEF在WPF中的应用能帮助开发者构建模块化、可扩展的程序,提高代码的可读性和可维护性。通过理解MEF的核心概念并实践相关的实例,我们可以更好地利用这一强大的框架来提升开发效率和应用质量。

    MEF6-1协议

    标题:MEF6-1协议 描述:城域以太网系列MEF6-1协议,EVC分类详解,基础知识 知识点: 一、MEF6-1协议简介 MEF6.1是城域以太网论坛(Metro Ethernet Forum,简称MEF)于2008年4月发布的技术规范,其主要目标是定义...

    扩展性MEF.rar111

    **标题与描述解析** 标题“扩展性MEF.rar111...综上所述,"扩展性MEF.rar111"这个压缩包可能包含了关于MEF的详细文档、示例代码或者教学资源,可以帮助学习者掌握如何在.NET项目中利用MEF构建可扩展和灵活的应用程序。

    MEF组件式开发,模块化开发

    MEF(Managed Extensibility Framework)是微软提供的一种组件化开发框架,主要用于构建可扩展的应用程序。MEF允许开发者将应用程序划分为独立的、可替换的组件,这些组件可以动态地发现并集成到系统中,从而实现了...

    MEF模块解耦,WCF Rest 扩展 基础示例

    MEF(Managed Extensibility Framework)是.NET框架中一个用于构建可扩展应用程序的库,它提供了模块化和解耦的功能。在本示例中,我们将深入探讨如何利用MEF实现应用模块之间的解耦,以及如何将WCF(Windows ...

    C#MEF简单例子

    MEF 是一个由 Microsoft 开发的框架,用于实现应用程序的可扩展性和模块化。它提供了一种简单的方式来组合不同的组件,以创建一个功能强大且灵活的应用程序。 MEF 的主要概念 1. 组件(Component): MEF 中的组件...

    MEF框架整理学习内容

    ### MEF框架知识点详解 ...总之,MEF为.NET平台带来了强大的扩展性和灵活性,极大地提高了应用程序的可维护性和可扩展性。无论是对于小型项目还是大型企业级应用,MEF都是一种值得考虑的技术方案。

Global site tag (gtag.js) - Google Analytics