简体   繁体   English

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

[英]MEF + WPF + MVVM: Where should AggregateCatalog reside?

I'm taking my first crack at using MEF, but I can't seem to determine where I should create my AggregateCatalog and CompositionContainer . 我正在尝试使用MEF,但是我似乎无法确定应该在哪里创建AggregateCatalogCompositionContainer I have found many examples showing what the code should be: 我发现了很多示例来说明代码应为:

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

But now I just need to know where to put it. 但是现在我只需要知道放在哪里。 Should it go: 应该去:

  1. in App.xaml.cs App.xaml.cs
  2. in MainWindow.xaml MainWindow.xaml
  3. or in one of my ViewModels. 或在我的其中一个ViewModels中。

Edit: Should have googled just a little longer, I think I found what I was looking for. 编辑:应该已经谷歌了一段时间,我想我找到了我想要的。

Hosting MEF within application and libraries. 在应用程序和库中托管MEF。

After reading this, Hosting MEF within application and libraries , I decided that the composition of MEF can go in App.xaml.cs . 阅读此内容后, 在应用程序和库中托管MEF ,我决定可以在App.xaml.cs中使用MEF的组成。

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

A few things to note: 注意事项:

  • StartupUri="MainWindow.xaml" should be removed from App.xaml 应该从App.xaml删除StartupUri="MainWindow.xaml"
  • You will need to create a property for your main window, import it, and set base.MainWindow to it. 您将需要为主窗口创建一个属性, importimport ,并将base.MainWindow设置base.MainWindow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM