没有棱镜的MEF和WPF

时间:2015-12-22 20:43:33

标签: wpf mef

有人可以告诉我一个在app.xaml.cs文件中构建MEF组合容器的示例,而不使用棱镜或控制台应用程序,这是没有问题的。

出口工作,但进口不是,我看到的所有例子都只与Prism合作,我不想使用。如果在App.xaml.cs文件中导入将起作用,但我不明白导入为什么在MainWindow.cs中工作并且一切都在根组件中。

如果我在MainWindow构造函数中执行合成,我可以编写它,但如果可能的话,我想在app.xaml.cs中编写。

以下是一个示例(我实际上使用的是mvvm,但此示例的行为与后面的代码相同)。

 public partial class App : Application
{
    public App()
    {
        ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose;

    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);



        Compose();

       var window = new MainWindow();
        window.Show();

    }

    public void Compose()
    {
        var catalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog("."));
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }


}

 [Export]
public class MessagePlugin
{
    public string GetMessage()
    {
        return "Successfully composed message";
    }

}

 public partial class MainWindow : Window
{
    [Import]
    public MessagePlugin plugin { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        Loaded += MainWindow_Loaded;

    }


    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var p = plugin; <-------------------------------NULL
        MessageBox.Show(p.GetMessage());

    }
}

1 个答案:

答案 0 :(得分:0)

public partial class App : Application
{
   private CompositionContainer container;

    [Import(typeof(Window))]
    public Window TheMainWindow { get; set; }


    public App()
    {
        ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose;
    }


    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        TheMainWindow = new MainWindow();

        Compose();

        Application.Current.MainWindow = TheMainWindow;
        Application.Current.MainWindow.Show();

    }

    public void Compose()
    {
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));  
        container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }

}

[导出(typeof运算(窗口))]     public partial class MainWindow:Window     {         [进口]         public MessagePlugin插件{get;组; }

    public MainWindow()
    {
        InitializeComponent();
        Loaded += MainWindow_Loaded;

    }


    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var p = plugin;

        if (p != null)
        {
            MessageBox.Show(p.GetMessage());
        }
        else
        {
            MessageBox.Show("Plugin NOT Composed");
        }


    }
}