在 WPF MVVM 中使用 MEF 时导入不起作用

Import not work when using MEF in WPF MVVM

我想在 WPF 上测试 MEF。 我使用一个项目作为接口:

// Project name MEFWpfTest.Interfaces
public interface IAppViewModel
{
    string Name { get; set; }
}

然后新建一个项目来实现这个接口:

// Project name MEFWpfTest.ViewModels
[Export("AppViewModel")]
public class AppViewModel : IAppViewModel
{
    public string Name { get; set; }
}

在App.xaml.cs,WPF项目中,我尝试在MEF中编写部分:

// Project name MEFWpfTest
public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        var aggregateCatalog = new AggregateCatalog();
        Assembly assembly = Assembly.GetExecutingAssembly();
        aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly));

        var directoryPath = Path.GetDirectoryName(assembly.Location);

        if (directoryPath != null)
        {
            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(directoryPath, $"MEFWpfTest.*.dll"));

        }

        CompositionContainer Container = new CompositionContainer(aggregateCatalog);
        Container.ComposeParts(this);

        MainWindow w = new MainWindow();
        w.Show();
    }
}

然后在 MainWindow.xaml.cs 中,我使用 IAppViewModel 导入:

// Project name MEFWpfTest
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    [Import("AppViewModel")]
    public Interfaces.IAppViewModel AppVM { get; set; }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    { // I set a break point here.

    }
}

当我 运行 这个应用程序时,我发现 AppVM 是空的。当我在 One assembly 中做同样的事情时,这很好。 MEFWpfTest 已引用 MEFWpfTest.Interfaces 和 MEFWpfTest.ViewModels.

我哪里做错了?

在其构造函数上组合部分:

public MainWindow()
{
    InitializeComponent();
    Container.ComposeParts(this); // get container somehow
}

请注意,导入 property/field 所有者 class 会自动导入其 properties/fields 而无需显式 ComposeParts()。如果 AppViewModel[Import] properties/fields,它们会自动设置。您不需要在 AppViewModel 的构造函数中调用 ComposeParts(this)ComposePart() 级联导入 classes.