MEF - 未找到与约束

时间:2017-01-06 08:59:11

标签: c# mef

所以我有一个类,我正在尝试导入一些构造函数:

[Export]
public partial class MainWindow
{
        private readonly MainWindowViewModel _viewModel;
        private readonly IEnumerable<IApplicationClosingListener> _applicationClosingListeners;
        private readonly Lazy<IPreferencesRepository> _preferencesRepository;

        [ImportingConstructor]
        public MainWindow(MainWindowViewModel viewModel, IViewManager viewManager, [ImportMany] IEnumerable<IApplicationClosingListener> applicationClosingListeners, Lazy<IPreferencesRepository> preferencesRepository)
        {
            _doStuff();
        }
}

我还要导出我要导入的所有类(MainWindowViewModelIViewManagerIPreferencesRepository)。我是这样做的:

MainWindowViewModelIViewManager类:

    [Export]
    [Export(typeof(IViewManager))]
    [Export(typeof(IMessagePresenter))]
    public class MainWindowViewModel : BaseViewModel, IViewManager, IApplicationClosingListener
    {
        [ImportingConstructor]
        public MainWindowViewModel(
            Lazy<IPreferencesRepository> preferencesRepository)
        {
            _doStuff();
        }

最后,IPreferencesRepository课程:

[Export(typeof(IPreferencesRepository))]
    public class PreferencesRepository : IPreferencesRepository
    {
        private readonly IPreferencesStorage _preferencesStorage;

        [ImportingConstructor]
        public PreferencesRepository(IPreferencesStorage preferencesStorage, IPreferencesSerializer preferencesSerializer)
        {
            _doStuff();
        }

现在当我尝试获取并使用导出的MainWindow类时出现问题:

var container = new CompositionContainer(new ApplicationCatalog());
container.ComposeExportedValue((IApplication)this);
var mainWindow = container.GetExport<MainWindow>(); // here the exception is thrown.

抛出ImportCardinalityMismatchException。此外,在调试控制台中,我收到三条消息,告诉我“ 没有找到符合约束条件的导出 ”。

我错过了什么?

1 个答案:

答案 0 :(得分:-1)

可能您没有导出IPreferencesSerializer 另外,我认为您的MainWindowViewModel应该导出IApplicationClosingListener