MEF + WPF + MVVM:AggregateCatalog应该驻留在哪里?

时间:2012-08-31 21:15:29

标签: c# wpf mef

我正在考虑使用MEF,但我似乎无法确定应该在哪里创建AggregateCatalogCompositionContainer。我找到了许多示例,说明代码应该是什么:

var moduleCatalog = new AggregateCatalog(
    new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()), 
    new DirectoryCatalog(moduleDir));
var container = new CompositionContainer(moduleCatalog);
container.ComposeParts(this);

但现在我只需要知道把它放在哪里。它应该去:

  1. in App.xaml.cs
  2. in MainWindow.xaml
  3. 或在我的一个ViewModel中。
  4. 编辑:应该再搜索一下,我想我找到了我想要的东西。

    Hosting MEF within application and libraries.

1 个答案:

答案 0 :(得分:1)

在阅读此内容Hosting MEF within application and libraries后,我决定MEF的内容可以放入App.xaml.cs

public partial class App : Application
{
    [Import]
    public Window TheMainWindow { get; set; }

    protected override void OnStartup(StartupEventArgs e)
    {
        var moduleCatalog = new AggregateCatalog(
            new AssemblyCatalog(typeof(App).Assembly), 
            new DirectoryCatalog(moduleDir));
        var container = new CompositionContainer(moduleCatalog);
        container.ComposeParts(this);
        base.MainWindow = TheMainWindow;
        TheMainWindow.Show();
    }
}

有几点需要注意:

  • StartupUri="MainWindow.xaml"应从App.xaml
  • 中删除
  • 您需要为主窗口import创建一个属性,并为其设置base.MainWindow