Search code examples
c#wpfmef

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. 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
  2. in MainWindow.xaml
  3. or in one of my ViewModels.

Edit: Should have googled just a little longer, I think I found what I was looking for.

Hosting MEF within application and libraries.


Solution

  • After reading this, Hosting MEF within application and libraries, I decided that the composition of MEF can go in 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();
        }
    }
    

    A few things to note:

    • StartupUri="MainWindow.xaml" should be removed from App.xaml
    • You will need to create a property for your main window, import it, and set base.MainWindow to it.