.NET Core 可扩展性框架

在本章中,我们将讨论托管可扩展性框架(MEF)。MEF 可以用于第三方插件扩展性,也可以为常规应用程序带来松散耦合的插件式架构的好处。

  • MEF 是一个用于创建轻量级、可扩展应用程序的库。
  • 它允许应用程序开发人员在不需要配置的情况下发现和使用扩展。
  • MEF 是.NET Framework 4的一个组成部分,在使用.NET Framework的任何地方都可以使用,从而提高大型应用程序的灵活性、可维护性和可测试性。
  • 您可以在客户端应用程序中使用 MEF,无论它们使用 Windows 窗体、WPF 或任何其他技术,还是在使用 ASP.NET 的服务器应用程序中。
  • MEF 也已作为 Microsoft.Composition 移植到.NET Core,但只是部分移植。
  • 仅移植 System.CompositionSystem.ComponentModel.Composition 尚不可用。这意味着,我们没有可以从目录中的程序集加载类型的目录。

在本章中,我们将只学习如何在 .NET Core 应用程序中使用 MEF

让我们了解一个简单的实例,其中我们将在 .NET Core 控制台应用程序中使用 MEF。现在让我们创建一个新的 .NET Core 控制台项目。

首先,在 Visual Studio 2019 中创建一个 .NET Core 控制台程序。

给项目命名为 MEFDemo

创建项目后,我们需要添加 Microsoft.Composition 的引用,以便使用 MEF。为此,让我们在解决方案资源管理器中右键单击项目并选择 管理 NuGet 程序包

在对话框中搜索 Microsoft.Composition

然后选择安装。

现在项目已经引用了 Microsoft.Composition

接下来,我们需要创建一个要导出的接口,并实现该接口,并用 export 属性修饰该类。现在让我们添加一个新类。

然后给 PrintData.cs 添加代码。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Composition;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace MEFDemo {
  7. public interface IPrintData {
  8. void Send(string message);
  9. }
  10. [Export(typeof(IPrintData))]
  11. public class PrintData : IPrintData {
  12. public void Send(string message) {
  13. Console.WriteLine(message);
  14. }
  15. }
  16. }

如上所述,目录在 Microsoft.Composition 命名空间中不可用。因此,它将使用导出属性从 Assembly 加载所有类型,并附加到导入属性,如 Program.cs 文件中的 Compose 方法所示。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Composition;
  4. using System.Composition.Hosting;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. namespace MEFDemo {
  9. public class Program {
  10. public static void Main(string[] args) {
  11. Program p = new Program();
  12. p.Run();
  13. }
  14. public void Run() {
  15. Compose();
  16. PrintData.Send("Hello,this is MEF demo");
  17. }
  18. [Import]
  19. public IPrintData PrintData { get; set; }
  20. private void Compose() {
  21. var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly };
  22. var configuration = new ContainerConfiguration()
  23. .WithAssembly(typeof(Program).GetTypeInfo().Assembly);
  24. using (var container = configuration.CreateContainer()) {
  25. PrintData = container.GetExport<IPrintData>();
  26. }
  27. }
  28. }
  29. }

现在运行,结果如下:

要了解有关 MEF 的更多信息,请访问以下 Url

https://learn.microsoft.com/en-us/dotnet/framework/mef/?redirectedfrom=MSDN