Search code examples
c#prismmef

ImportCardinalityMismatchException when using RegisterBootstrapperProvidedTypes with PRISM MEF


when I override RegisterBootstrapperProvidedTypes and I try to register my own WCServiceAgent the Bootstrapper throws a

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

The exception occurs with:

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

and also with

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

in my Bootstrapper class

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();
    }
}

How can I fix this? Whats the cause of the exception?


Solution

  • You need to call the base implementation first.

    protected override void RegisterBootstrapperProvidedTypes()
    {
        base.RegisterBootstrapperProvidedTypes();
    
        // your custom registrations go here...        
    }
    

    If you take a look at the implementation of the bootstrapper base class, you'll see that there are 4 exports which need to be composed:

    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);