2012-08-31 89 views
2

我正在使用MEF的第一個破解,但我似乎無法確定我應該在哪裏創建我的AggregateCatalogCompositionContainer。我發現有很多例子顯示的代碼應該是什麼:MEF + WPF + MVVM:AggregateCatalog應該放在哪裏?

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. 或在我的ViewModels之一。

編輯:應該只是時間稍長用Google搜索,我想我找到了我一直在尋找。

Hosting MEF within application and libraries.

回答

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它。