在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

相关文章:

  • 2022-12-23
  • 2021-10-27
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-31
  • 2021-11-22
  • 2021-12-05
  • 2022-01-31
  • 2022-12-23
相关资源
相似解决方案