使用MEF在初始化时遇到问题在Prism中查看

时间:2015-10-09 19:41:00

标签: c# wpf mvvm prism mef

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

以下是应用程序的Shell:

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

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

这是我的Bootstrapper类:

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的类:

[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的View,如下所示:

<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类:

[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中是否需要它。如果需要那么How ???

演示项目:

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

1 个答案:

答案 0 :(得分:4)

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

由于MyView构造函数需要IMyViewModel类型:

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

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

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