将RegisterBootstrapperProvidedTypes与PRISM MEF一起使用时,ImportCardinalityMismatchException

时间:2015-09-03 07:15:19

标签: c# prism mef

当我覆盖RegisterBootstrapperProvidedTypes并尝试注册我自己的WCServiceAgent时,Bootstrapper会抛出

ImportCardinalityMismatchException
Additional information: No exports were found that match the constraint: 
ContractName    Microsoft.Practices.ServiceLocation.IServiceLocator
RequiredTypeIdentity    Microsoft.Practices.ServiceLocation.IServiceLocator

例外情况发生在:

 protected override void RegisterBootstrapperProvidedTypes()
    {
        this.Container.ComposeExportedValue<IModuleCatalog>(this.ModuleCatalog);
        this.Container.ComposeExportedValue<AggregateCatalog>(this.AggregateCatalog);
    }

以及

    protected override void RegisterBootstrapperProvidedTypes()
    {
         this.Container.ComposeExportedValue<MyWCFServiceAgent>(new MyWCFServiceAgent(1));
    }

在我的Bootstrapper类中

public class Bootstrapper : MefBootstrapper
{
    //protected override void RegisterBootstrapperProvidedTypes()
    //{
    //see above code
    //}

    protected override System.Windows.DependencyObject CreateShell()
    {
        return this.Container.GetExportedValue<ShellWindow>();
    }
    protected override void ConfigureAggregateCatalog()
    {
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
        base.ConfigureAggregateCatalog();
    }
    protected override Microsoft.Practices.Prism.Regions.IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
    {
        var factory = base.ConfigureDefaultRegionBehaviors();
        //factory.AddIfMissing("AutoPopulateExportedViewsBehavior", typeof(AutoPopulateExportedViewsBehavior));
        return factory;
    }
    protected override IModuleCatalog CreateModuleCatalog()
    {
        return base.CreateModuleCatalog();
    }
    protected override void InitializeShell()
    {
        base.InitializeShell();
        App.Current.MainWindow = (Window)this.Shell;
        App.Current.MainWindow.Show();
    }
}

我该如何解决这个问题?什么是例外的原因?

1 个答案:

答案 0 :(得分:1)

您需要先调用基础实现。

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

    // your custom registrations go here...        
}

如果你看一下bootstrapper基类的implementation,你会看到有4个需要编写的导出:

this.Container.ComposeExportedValue<ILoggerFacade>(this.Logger);
this.Container.ComposeExportedValue<IModuleCatalog>(this.ModuleCatalog);
this.Container.ComposeExportedValue<IServiceLocator>(new MefServiceLocatorAdapter(this.Container));
this.Container.ComposeExportedValue<AggregateCatalog>(this.AggregateCatalog);