使用 MEF 在 Prism 中查看在初始化时出现问题

View in Prism using MEF having problems while initializing

我使用 WPF Prism 创建了一个小型演示应用程序,我正在使用 Mef。

这是应用程序的 Shell:

<Window ..........>
    <Grid>
        <ContentControl 
            prism:RegionManager.RegionName="{x:Static inf:RegionNames.ContentRegion}" />
    </Grid>
</Window>

这里的 ContentRegion 只是在另一个 class 基础设施项目中定义的静态字符串。

这是我的引导程序 class:

public class Bootstrapper : MefBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return Container.GetExportedValue<Shell>();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();

        App.Current.MainWindow = (Window)Shell;
        App.Current.MainWindow.Show();
    }

    protected override void ConfigureAggregateCatalog()
    {
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(RegionNames).Assembly));
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleMyModule).Assembly));
    }
}

如您所见,我已将我的主要执行项目及其基础结构项目添加到此 Bootstrapper。

现在我已经创建了一个名为 MyModule 的非常简单的模块。 它有一个名为 ModuleMyModule 的 class:

[ModuleExport(typeof(ModuleMyModule), InitializationMode = InitializationMode.WhenAvailable)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ModuleMyModule : IModule
{
    IRegionManager _regionManager;

    [ImportingConstructor]
    public ModuleMyModule(IRegionManager regionManager)
    {
        _regionManager = regionManager;
    }

    public void Initialize()
    {
        _regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(MyView));
    }
}

现在,我在这个应用程序中有一个名为 MyView 的视图,如下所示:

<UserControl ............>
    <Grid>
        <CheckBox Content="Have you Checked it properly?"/>
    </Grid>
</UserControl>

到目前为止,我的应用程序运行良好。

问题现在开始:

现在,我向这个项目添加了一个 ViewModel。所以,现在我的视图 MyView 看起来像:

<UserControl ............>
    <Grid>
        <CheckBox IsChecked="{Binding IsProperlyChecked}" Content="Have you Checked it properly?"/>
    </Grid>
</UserControl>

这是 MyView 的 .cs 文件:

[Export(typeof(MyView))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MyView : UserControl, IView
{
    [ImportingConstructor]
    public MyView(IMyViewModel viewModel)
    {
        InitializeComponent();
        ViewModel = viewModel;
    }

    public IViewModel ViewModel
    {
        get
        {
            return (IViewModel)DataContext;
        }
        set
        {
            DataContext = value;
        }
    }
}

这是我的 ViewModel class:

[Export(typeof(MyViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MyViewModel : IMyViewModel, INotifyPropertyChanged
{
    [ImportingConstructor]
    public MyViewModel()
    {
        IsProperlyChecked = true;
    }

    private bool _IsProperlyChecked;

    public bool IsProperlyChecked
    {
        get
        {
            return _IsProperlyChecked;
        }
        set
        {
            if (_IsProperlyChecked != value)
            {
                _IsProperlyChecked = value;
                OnPropertyChanged("IsProperlyChecked");
            }
        }
    }

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

IMyViewModel是一个界面如下图:

public interface IMyViewModel : IViewModel
{
    bool IsProperlyChecked { get; set; }
}

现在,我的项目停止工作了:

我收到一个错误:

An exception has occurred while trying to add a view to region 'ContentRegion'. 

    - The most likely causing exception was was: 'Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type MyView, key "" ---> Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type MyView, key ""

   at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter.DoGetInstance(Type serviceType, String key)

   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)

   --- End of inner exception stack trace ---

   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)

   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType)

   at Microsoft.Practices.Prism.Regions.RegionViewRegistry.CreateInstance(Type type)

   at Microsoft.Practices.Prism.Regions.RegionViewRegistry.<>c__DisplayClass1.<RegisterViewWithRegion>b__0()

   at Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior.OnViewRegistered(Object sender, ViewRegisteredEventArgs e)'.

为什么会抛出这个异常??

我觉得我做错了什么。我是 MEF 的新手,我以前用过 Unity。

我需要注册 ViewModel 及其接口。但我不知道 MEF 是否需要它。如果需要那么如何???

演示项目:

https://drive.google.com/file/d/0Bw2XAE1EBI6rU3VsYjVyQmhFRFE/view?usp=sharing

使用 MEF 时,在 ExportAttribute 中作为参数传递的类型应与导入所需的类型匹配。

因为 MyView 构造函数需要 IMyViewModel 类型:

 [ImportingConstructor]
 public MyView(IMyViewModel viewModel)
 {
 ..

...尝试将 MyViewModel class 导出为 IMyViewModel

 [Export(typeof(IMyViewModel))] 
 [PartCreationPolicy(CreationPolicy.NonShared)]
 public class MyViewModel : IMyViewModel, INotifyPropertyChanged
 {
  ...