在本章中,我们将讨论托管可扩展性框架(MEF). MEF可以用于第三方插件的可扩展性,或者它可以将松散耦合的类似插件的体系结构的好处带给常规应用程序.
MEF是一个用于创建轻量级,可扩展应用程序的库.
它允许应用程序开发人员在不需要配置的情况下发现和使用扩展./p>
MEF是.NET Framework 4不可或缺的一部分,在使用.NET Framework的任何地方都可用,它可以提高大型应用程序的灵活性,可维护性和可测试性.
您可以在客户端应用程序中使用MEF,无论是使用Windows窗体,WPF还是任何其他技术,还是在使用ASP.NET的服务器应用程序中.
MEF已被 Microsoft.Composition 移植到.NET Core但部分移植到了.
仅移植 System.Composition ,并且 System.ComponentModel.Composition 尚不可用.这意味着,我们没有可以从目录中的程序集加载类型的目录.
在本章中,我们只会了解我们如何在.NET Core应用程序中使用MEF.
让我们了解一个简单的例子,我们将在.NET Core控制台应用程序中使用MEF.现在让我们创建一个新的.NET Core控制台项目.
在左侧窗格中,选择 Templates → Visual C# → .NET Core,然后在中间窗格中,选择Console Application(.NET Core).
在Name字段中输入项目名称,然后单击OK.
创建项目后,我们需要添加引用Microsoft.Composition使我们可以使用MEF.为此,让我们在解决方案资源管理器中右键单击项目,然后管理NuGet包...
搜索 Microsoft.Composition 然后单击安装.
点击确定按钮.
点击我接受按钮.
安装完成后,您会在参考文献中找到错误.
让我们打开 project.json 文件.
{ "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.Composition": "1.0.30", "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" } }, "frameworks": { "netcoreapp1.0": { "imports": "dnxcore50" } } }
您可以看到添加了 Microsoft.Composition 依赖项,但问题是此程序包与 dnxcore50 .所以我们需要导入 portablenet45 + win8 + wp8 + wpa81 .现在让我们用以下代码替换你的 project.json 文件.
{ "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.Composition": "1.0.30", "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" } }, "frameworks": { "netcoreapp1.0": { "imports": "portable-net45+win8+wp8+wpa81" } } }
保存此文件,您将看到错误已得到纠正.
如果展开引用,则会看到 Microsoft.Composition的引用.
首先我们需要创建要导出的接口并实现接口并使用export属性修饰类.现在让我们添加一个新类.
在"名称"字段中输入您的班级名称,然后单击添加.
让我们在 PrintData.cs 文件中添加以下代码.
using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading.Tasks; namespace MEFDemo { public interface IPrintData { void Send(string message); } [Export(typeof(IPrintData))] public class PrintData : IPrintData { public void Send(string message) { Console.WriteLine(message); } } }
如上所述,目录在Microsoft.Composition命名空间中不可用.因此,它将使用export属性加载Assembly中的所有类型,并附加到import.cs文件中的Compose方法中显示的import属性.
using System; using System.Collections.Generic; using System.Composition; using System.Composition.Hosting; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace MEFDemo { public class Program { public static void Main(string[] args) { Program p = new Program(); p.Run(); } public void Run() { Compose(); PrintData.Send("Hello,this is MEF demo"); } [Import] public IPrintData PrintData { get; set; } private void Compose() { var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly }; var configuration = new ContainerConfiguration() .WithAssembly(typeof(Program).GetTypeInfo().Assembly); using (var container = configuration.CreateContainer()) { PrintData = container.GetExport<IPrintData>(); } } } }
现在让我们运行你的应用程序,你会看到它通过实例化 PrintData 类来运行.
要了解有关MEF的更多信息,请访问以下网址: https://msdn.microsoft. com/en-us/library/dd460648%28v = vs.110%29.aspx 了解更多详情.