`

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

阅读更多

Simple Introduction to Extensible Applications with the Managed Extensions Framework

 

Recently my team has been working on the Managed Extensions Framework (MEF)... I have gotten a chance to explain the concept to folks and I think I have discovered a way to talk about MEF that folks can easily get.  So I thought I'd spend a little time walking through a *very* simple MEF example as a way to introduce folks to the power of extensible applications in general, and MEF in particular. 

BTW, you can download the current MEF CTP  and the final working sample.

Background

Let's start with the most simple example: Hello World! 

   1: using System;
   2:  
   3: class Program
   4: {
   5:     public void Run()
   6:     {
   7:         Console.WriteLine("Hello World!");
   8:         Console.ReadKey();
   9:     }
  10:     static void Main(string[] args)
  11:     {
  12:         Program p = new Program();
  13:         p.Run();
  14:     }
  15: }

Now, you might now always want to print the same string, so let's refactor slightly to pull the string out.. 

   1: public string Message { get; set; }
   2:  
   3: public void Run()
   4: {
   5:     Console.WriteLine(Message);
   6:     Console.ReadKey();
   7: }

This looks nice, now we need to add the message... well, the actual text is a separate concern, as such it should be in a different class.    Such as:

   1: public class SimpleHello 
   2: {
   3:     public string Message
   4:     {
   5:         get
   6:         {
   7:             return "hello world!!";
   8:         }
   9:     }
  10: }

Now we simply need wire these up:

   1: public void Run()
   2: {
   3:     SimpleHello hello = new SimpleHello();
   4:     Message = hello.Message;
   5:  
   6:     Console.WriteLine(Message);
   7:     Console.ReadKey();
   8: }

This works, but something looks odd about line 3 and 4... We have introduced tight coupling back.. What we really want to do is externalize lines 3 and 4, so they can be controlled without effecting the rest of the logic of the program. 

 

Enter MEF

一、基本用例

STEP 1:

Add a Reference to the System.ComponentModel.Composition.dll assembly found in the bin directory of the MEF zip. 

Add

   1: using System.ComponentModel.Composition;

Now in the Program class, we need to import a value for Message -- that is, we want to specify that someone outside of this program needs to supply a message.  Then we need to remove our tight coupling.    Note in line 4-5 and we saying we want to import the value for Message.  Here I am showing doing it by type (string).. because basic types such as strings might be pretty common, consider using a named import such as [Import("Message")]

   1: class Program
   2: {
   3:  
   4:     [Import]
   5:     public string Message { get; set; }
   6:  
   7:     public void Run()
   8:     {
   9:        // SimpleHello hello = new SimpleHello();
  10:         //Message = hello.Message;
  11:  
  12:         Console.WriteLine(Message);
  13:         Console.ReadKey();
  14:     }

 

STEP 2:

Now in the SimpleHello class we need to export the Message property.  This tells the system it can be used to satisfy requirements.    Notice line 3 and 4 and am marking it with an Export attribute..  Again, this exports it by type (string in this case).  As with above, you might want to do it with an explicit name for a more real world example [Export("Message")]

   1: public class SimpleHello 
   2: {
   3:     [Export]
   4:     public string Message
   5:     {
   6:         get
   7:         {
   8:             return "hello world!!";
   9:         }
  10:     }
  11: }

 

STEP 3:

Now we need to tell MEF to wire these up for us.

   1: public void Run()
   2: {
   3:     //SimpleHello hello = new SimpleHello();
   4:     //Message = hello.Message;
   5:     var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
   6:     var container = new CompositionContainer(catalog.CreateResolver());
   7:     container.AddPart(this);
   8:     container.Compose();
   9:  
  10:  
  11:     Console.WriteLine(Message);
  12:     Console.ReadKey();
  13: }

In line 5, we create a catalog -- that tells MEF where to look for imports and exports.  In this case, we are saying the currently running assembly.  There are tons of different parts catalogs, we will look at some later and you can of course build your own.

in line 6, we create a Composition container-- this is effectively the soup that all the different parts will be wired up together.

In line 7, we add this instance of Program to the container so that its dependencies get wired up.

In line 8, we do the compose magic.  this is where the Message property of Program gets set. 

Notice, in this case the wire up is done by matching types (String to String)... clearly that isn't always the right way, we will look at other ways to wire up later.

Run it and you get the expected output of "hello world!".

 

二、小小的扩展

 

STEP 1:

Now let's add another message, just to be a little more fun... 

   1: public class MoreMessages
   2: {
   3:     [Export]
   4:     public string FunMessage
   5:     {
   6:         get
   7:         {
   8:             return "This is getting fun!";
   9:         }
  10:     }
  11: }

Now run.. It blows up!  Why?  Well, let's look at the exception:

System.ComponentModel.Composition.CompositionException  Error : Multiple exports were found that match the constraint '(composableItem.ContractName = \"System.String\")'. The import for this contract requires a single export only."

 

STEP 2:

From the error it looks like we provided too many ways to satisfy the Import... MEF didn't know which one to pick.  Of course you can programmatically get in there and help, you can also just remove the export from one of the messages... but more fun, you can actually tell MEF you are able to deal with zero or more results.  Change the Message property of Program as follows:

   1: [Import]
   2: public IEnumerable<string> Messages { get; set; }

Notice we changed the return type to be a collection of strings rather than just one string.

Now change the usage code slightly and we get:

   1: class Program
   2: {
   3:  
   4:     [Import]
   5:     public IEnumerable<string> Messages { get; set; }
   6:  
   7:     public void Run()
   8:     {
   9:         //SimpleHello hello = new SimpleHello();
  10:         //Message = hello.Message;
  11:         var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
  12:         var container = new CompositionContainer(catalog.CreateResolver());
  13:         container.AddPart(this);
  14:         container.Compose();
  15:  
  16:         foreach (var s in Messages)
  17:         {
  18:             Console.WriteLine(s);
  19:         }
  20:  
  21:     
  22:         Console.ReadKey();
  23:     }

 

输出为:

hello world!!

This is getting fun!

 

Wow -- we get both messages!  Pretty cool...

 

 

 

 

分享到:
评论

相关推荐

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

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

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

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

    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 2 _Preview2

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

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

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

    MEF6-1协议

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

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

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

    WPF prism MEF 架构

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

    MEF 结合 MVVMLight

    1. **模块化**:通过MEF,可以将应用程序分解为独立的、可插拔的模块,每个模块都有自己的视图、视图模型和业务逻辑,增强了系统的可维护性和可扩展性。 2. **解耦**:MEF的依赖注入与MVVMLight的MVVM模式相结合,...

    MEF简单应用

    MEF的主要目标是简化软件的可插拔性和模块化,允许开发者轻松地引入第三方组件或扩展现有功能,而无需深入修改应用程序的核心代码。在本篇中,我们将探讨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.rar111

    1. **插件架构**: MEF非常适合构建插件式架构,允许用户安装、卸载和更新应用程序的扩展部分。 2. **模块化应用**: 当需要将大型应用拆分为多个独立模块时,MEF可以简化模块之间的通信和依赖管理。 3. **动态加载*...

    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都是一种值得考虑的技术方案。

    WPF中MEF的应用,简单实例

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

Global site tag (gtag.js) - Google Analytics