2

我第一次尝试使用 MEF,但我似乎无法确定应该在哪里创建我的AggregateCatalogand CompositionContainer. 我发现了很多例子来说明代码应该是什么:

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

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

  1. App.xaml.cs
  2. MainWindow.xaml
  3. 或在我的一个 ViewModel 中。

编辑:应该再用谷歌搜索一下,我想我找到了我想要的东西。

在应用程序和库中托管 MEF。

4

1 回答 1

1

看完这篇,Hosting MEF inside 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为它。
于 2012-08-31T22:25:12.387 回答