MEF初体验之一:在应用程序宿主MEF

在MEF出现以前,其实微软已经发布了一个类似的框架,叫MAF(Managed Add-in Framework),它旨在使应用程序孤立和更好的管理扩展,而MEF更关心的是可发现性、扩展性和轻便性,后者更lightweight。我们将跟随MEF官网来学习。

The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.

1.How to host MEF

First,add reference to System.ComponentModel.Composition assembly,then instantiate CompositionContainer,add some composable parts you want and hosting application to the container,in the end compose them.

2.An simple example

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace HostingMef
{
    class Program
    {
        [Import]
        public IMessageSender MessageSender { get; set; }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Composite();
            p.MessageSender.Send("Message Sent");
            Console.ReadKey();
        }
        void Composite()
        { 
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this, new EmailSender());
        }
    }
    interface IMessageSender
    {
        void Send(string msg);
    }
    [Export(typeof(IMessageSender))]
    class EmailSender : IMessageSender
    {
        public void Send(string msg)
        {
            Console.WriteLine(msg);
        }
    }

}
View Code

结果正如预期:

在MEF组合模型中,CompositionContainer是核心,它包含了一些可用的Parts并且组合它们,也就是说使宿主程序中的Imports能匹配到Exports。而CompositionContainer是怎么发现哪些parts是available的呢?答案是它通过Catalogs,Catalogs通过提供的type、assembly或者directory来发现来自不同源的parts.在上面的例子中,通过使用Export特性和Import特性来实现了DI,避免了MessageSender在编译时对EmailSender的依赖。当然,这里只使用了一个Export特性和一个Import特性,并不一直这样,在后面我们将看到多个的情况。

原文地址:https://www.cnblogs.com/jellochen/p/3660282.html