没有棱镜的 MEF 和 WPF

MEF and WPF without Prism

谁能告诉我一个在 app.xaml.cs 文件中构建 MEF 组合容器的示例,而无需使用 prism 或控制台应用程序,这没有问题。

导出有效,但导入无效,我看到的所有示例都只适用于我不想使用的 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());

    }
}
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);
    }

}

[导出(类型(Window))] public 部分 class 主要 Window : 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");
        }


    }
}