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:
App.xaml.cs
MainWindow.xaml
Edit: Should have googled just a little longer, I think I found what I was looking for.
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
import
it, and set base.MainWindow
to it.