在应用程序中托管(Hosing) MEF 涉及到创建组合容器(CompositionContainer) 实例,添加可组合部件(Composable Parts),包括应用程序宿主(Host)本身并进行组合(Composing)。
class Program { static void Main(string[] args) { Program p = new Program(); p.Run(); } [Import] public IMessageSender MessageSender { get; set; } public void Run() { Compose(); MessageSender.Send("Message Sent"); } private void Compose() { var container = new CompositionContainer(); container.ComposeParts(this, new EmailSender()); } }
public interface IMessageSender { void Send(string message); } [Export(typeof(IMessageSender))] public class EmailSender : IMessageSender { public void Send(string message) { Console.WriteLine(message); } }
[Import] public IMessageSender MessageSender { get; set; }
private void Compose() { var container = new CompositionContainer(); container.ComposeParts(this, new EmailSender()); }
private void Compose() { AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); container.ComposeParts(this); }
using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System; using System.Reflection; namespace HostingMefInAnApplication { class Program { static void Main(string[] args) { Program p = new Program(); p.Run(); } [Import] public IMessageSender MessageSender { get; set; } public void Run() { Compose(); MessageSender.Send("Message Sent"); } private void Compose() { AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } public interface IMessageSender { void Send(string message); } [Export(typeof(IMessageSender))] public class EmailSender : IMessageSender { public void Send(string message) { Console.WriteLine(message); } } }
MEF 编程指南:在应用中托管 MEF,布布扣,bubuko.com
原文:http://www.cnblogs.com/JavCof/p/3666089.html