Microsoft可扩展性框架(MEF)可组合概念背后的理论是什么?

时间:2014-07-24 18:27:59

标签: c# .net vb.net

我正在阅读有关构建可组合应用程序的MSDN文章:http://msdn.microsoft.com/en-us/magazine/ee291628.aspx。我只是不明白这一点,它似乎只是暴露了一个合同和一堆导入/导出方法,但我不确定如何在实际意义上使用......这与继承自第三方控制/表格?有人有一个他们可以分享的实际例子,以澄清这可能是有益的,而不是仅仅继承第三方控件吗?

2 个答案:

答案 0 :(得分:2)

MEF是dependency injection框架。简单解释一下,我会说它是在运行时扩展您的应用程序。您可以想象有人想在您编写应用程序之后扩展您的应用程序,并且可以通过编写自己的应用程序并尊重您的应用程序所指定的合同来实现此目的。

要继承,您需要对事先知道的程序集的引用。这不是MEF的情况,它使用契约(接口),并且可以在应用程序中动态加载程序集。然后,您可以开始忘记一遍又一遍地编译以向您的应用程序添加新功能。你开始扩展 ......

以下是来自microsoft的一个很好的教程:How to: Use MEF with MVC

答案 1 :(得分:1)

我有点得到它...这看起来像依赖注入...所以我想传递给CompositionContainer.ComposeParts()的所有东西都需要用“Export”属性标记。我希望ComposeParts()填写的任何东西都需要用“Import”属性标记。所以这样的事情(愚蠢的例子,但我认为它说明了这一点) 首先,参考文献:

imports System
imports System.ComponentModel.Composition
imports System.ComponentModel.Composition.Hosting

现在代码(注意“导出”属性)

Public MustInherit Class Place
      Public MustOverride Property Name as String
End Class

<Export>
Public Class Library
     Inherits Place  

     Public Overrides Property Name as String = "Library"
End Class

<Export>
Public Class Home
      Inherits Place

    Public Overrides Property Name as String = "Home"
End Class

现在是“人”(注意“导出”属性):

Public MustInherit Class Person
    Public MustOverride Property Name as String
End Class

<Export>
Public Class Joe
     Inherits Person

     Public Overrides Property Name as String = "Joe"
End Class

<Export>
Public Class Bob
     Inherits Person

     Public Overrides Property Name as String = "Bob"
End Class

现在我们可以编写一些有趣的东西(注意“导入”属性 - 这是注入发生的地方):

<Export>
Public Class WhereAmI
  <Import>
  Public person as Person

  <Import>
  Public place as Place

  Public Sub TellMe()
        Console.WriteLine(person.Name & " is in " & place.Name)
  End Sub
End Class

现在为可组合魔术:

Public Shared Sub Main()
    Dim compositionContainer as new CompositionContainer()
    compositionContainer.ComposeParts(new Bob(), new Library(), new WhereAmI())
    Dim whereAmI as WhereAmI = compositionContainer.GetExportedValueOrDefault(Of WhereAmI)()
    whereAmI.TellMe()    'would print "Bob is in Library"'

    Dim compositionContainer2 as new CompositionContainer()
    compositionContainer2.ComposeParts(new Bob(), new Home(), new WhereAmI())
    Dim whereAmI2 as WhereAmI = compositionContainer2.GetExportedValueOrDefault(Of WhereAmI)()
    whereAmI2.TellMe()    'would print "Bob is in Home"'
End Sub