Intermittent IServiceLocator Exception On Startup

Topics: Prism v4 - WPF 4
Feb 22, 2011 at 10:37 AM
Edited Feb 22, 2011 at 10:53 AM

We're experiencing an intermittent crash when starting our Prism v4 application - it happens rarely and more frequently on certain systems.

We've tried to debug, however, we haven't found the source of the problem.

Thanks in advance for any advice / suggestions.

 

The exception is as follows:

 Microsoft.Practices.Prism.Regions.Behaviors.RegionCreationException: An exception occurred while creating a region with name 'Toolbar'. The exception was: Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type AutoPopulateRegionBehavior, key "" ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior,(none)
  Resolving parameter "regionViewRegistry" of constructor Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior(Microsoft.Practices.Prism.Regions.IRegionViewRegistry regionViewRegistry)
    Resolving Microsoft.Practices.Prism.Regions.RegionViewRegistry,(none) (mapped from Microsoft.Practices.Prism.Regions.IRegionViewRegistry, (none))
    Resolving parameter "locator" of constructor Microsoft.Practices.Prism.Regions.RegionViewRegistry(Microsoft.Practices.ServiceLocation.IServiceLocator locator)
      Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)
 ---> System.InvalidOperationException: The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
   at BuildUp_Microsoft.Practices.ServiceLocation.IServiceLocator(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
   at BuildUp_Microsoft.Practices.Prism.Regions.RegionViewRegistry(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
   at BuildUp_Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
   --- End of inner exception stack trace ---
   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
   at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
   at Microsoft.Practices.Unity.UnityServiceLocator.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.RegionBehaviorFactory.CreateFromKey(String key) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionBehaviorFactory.cs:line 91
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.AttachDefaultBehaviors(IRegion region, T regionTarget) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 103
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.Initialize(T regionTarget, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 65
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.Microsoft.Practices.Prism.Regions.IRegionAdapter.Initialize(Object regionTarget, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 81
   at Microsoft.Practices.Prism.Regions.Behaviors.DelayedRegionCreationBehavior.CreateRegion(DependencyObject targetElement, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\Behaviors\DelayedRegionCreationBehavior.cs:line 137.  ---> Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type AutoPopulateRegionBehavior, key "" ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior,(none)
  Resolving parameter "regionViewRegistry" of constructor Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior(Microsoft.Practices.Prism.Regions.IRegionViewRegistry regionViewRegistry)
    Resolving Microsoft.Practices.Prism.Regions.RegionViewRegistry,(none) (mapped from Microsoft.Practices.Prism.Regions.IRegionViewRegistry, (none))
    Resolving parameter "locator" of constructor Microsoft.Practices.Prism.Regions.RegionViewRegistry(Microsoft.Practices.ServiceLocation.IServiceLocator locator)
      Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)
 ---> System.InvalidOperationException: The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
   at BuildUp_Microsoft.Practices.ServiceLocation.IServiceLocator(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
   at BuildUp_Microsoft.Practices.Prism.Regions.RegionViewRegistry(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
   at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
   at BuildUp_Microsoft.Practices.Prism.Regions.Behaviors.AutoPopulateRegionBehavior(IBuilderContext )
   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
   --- End of inner exception stack trace ---
   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
   at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
   at Microsoft.Practices.Unity.UnityServiceLocator.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.RegionBehaviorFactory.CreateFromKey(String key) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionBehaviorFactory.cs:line 91
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.AttachDefaultBehaviors(IRegion region, T regionTarget) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 103
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.Initialize(T regionTarget, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 65
   at Microsoft.Practices.Prism.Regions.RegionAdapterBase`1.Microsoft.Practices.Prism.Regions.IRegionAdapter.Initialize(Object regionTarget, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\RegionAdapterBase.cs:line 81
   at Microsoft.Practices.Prism.Regions.Behaviors.DelayedRegionCreationBehavior.CreateRegion(DependencyObject targetElement, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\Behaviors\DelayedRegionCreationBehavior.cs:line 137
   --- End of inner exception stack trace ---
   at Microsoft.Practices.Prism.Regions.Behaviors.DelayedRegionCreationBehavior.CreateRegion(DependencyObject targetElement, String regionName) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\Behaviors\DelayedRegionCreationBehavior.cs:line 143
   at Microsoft.Practices.Prism.Regions.Behaviors.DelayedRegionCreationBehavior.TryCreateRegion() in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\Behaviors\DelayedRegionCreationBehavior.cs:line 118
   at Microsoft.Practices.Prism.Regions.Behaviors.DelayedRegionCreationBehavior.ElementLoaded(Object sender, RoutedEventArgs e) in C:\Documents and Settings\hpuser\My Documents\Documents VII\Company.NewApp\Microsoft.Practices.Prism\Prism\Regions\Behaviors\DelayedRegionCreationBehavior.cs:line 150
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
   at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
   at MS.Internal.LoadedOrUnloadedOperation.DoWork()
   at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
   at System.Windows.Interop.HwndTarget.OnResize()
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Window.Show()

Feb 22, 2011 at 7:26 PM

Hi,

Could you provide us with more detailed information when you are experiencing this issue?

It will be very helpful if you could upload a repro sample of your application or at least provide some code, specially the application´s Bootstrapper in order to have more information to help you with this issue.

Thanks,

Miguel Bronzovic
http://blogs.southworks.net/mbronzovic

 

Feb 22, 2011 at 11:39 PM
Edited Feb 22, 2011 at 11:40 PM

We're using Unity for our bootstrapper:

            IUnityContainer unityContainer = new UnityContainer();
            var unityAdapter = new UnityAdapter(unityContainer);

            ServiceLocator.SetLocatorProvider(
                () => new UnityServiceLocator(unityContainer)
            );

            _logger.Log("Registering the ModuleManager", Category.Debug);
            unityContainer.RegisterType<IModuleManager, ModuleManager>();

            _logger.Log("Creating the ModuleCatalog", Category.Debug);
            ModuleCatalog moduleCatalog = new ModuleCatalog();


            _logger.Log("Adding the ToolBar module to the module catalog", Category.Debug);
            moduleCatalog = moduleCatalog.AddModule(typeof(ToolbarModule));

 

We're also using Caliburn v2 in conjunction with Prism v4:


                        CaliburnFramework
                            .Configure(unityAdapter)
                            .With.Core()
                            .With.PresentationFramework()
                            .With.CompositeApplicationLibrary(CreateShell)
                            .WithModuleCatalog(moduleCatalog)
                            .Start();

 

The CompositeApplicationLibrary in Caliburn is as follows:

 

namespace Caliburn.Prism
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using Core;
    using Core.Configuration;
  
    using Microsoft.Practices.Prism;
    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Prism.Logging;
    using Microsoft.Practices.Prism.Modularity;
    using Microsoft.Practices.Prism.Regions;
    using Microsoft.Practices.Prism.Regions.Behaviors;
    using Microsoft.Practices.ServiceLocation;
    using IModule=Microsoft.Practices.Prism.Modularity.IModule;
    using System.Reflection;
    using Caliburn.Core.InversionOfControl;

    /// <summary>
    /// The configuration for the composite application library.
    /// </summary>
    public class CompositeApplicationLibraryConfiguration : CaliburnModule<CompositeApplicationLibraryConfiguration>
    {
        private Type _loggerFacade;
        private Type _moduleInitializer;
        private Type _moduleManager;
        private Type _regionManager;
        private Type _eventAggregator;
        private Type _regionViewRegistry;
        private Type _regionBehaviorFactory;
        private Type _regionNavigationService;
        private Type _regionNavigationContentLoader;
        private Type _regionNavigationJournal;
        private Type _regionNavigationJournalEntry;
       
        private Func<DependencyObject> _createShell = () => null;
        private Action<IRegionBehaviorFactory> _afterConfigureBehaviors;
        private Action<IRegionBehaviorFactory> _overrideRegionBehavior;
        private Action<RegionAdapterMappings> _afterConfigureRegionAdapterMappings;
        private Action<RegionAdapterMappings> _overrideRegionAdapterMappings;
       
        private IModuleCatalog _moduleCatalog;
        private Type[] _moduleTypes;
        private Action _overrideModuleInit;
        private Type _modelRegionManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="CompositeApplicationLibraryConfiguration"/> class.
        /// </summary>
        public CompositeApplicationLibraryConfiguration()
        {
            UsingLoggerFacade<ConsoleLogger>();

            /* Caliburn uses a custom ModuleInitializer in order to register the component
             * add load the modules assembly */
            UsingModuleInitializer<CaliburnModuleInitializer>();
            UsingModuleManager<ModuleManager>();
            UsingRegionManager<RegionManager>();
            UsingModelRegionManager<DefaultModelRegionManager>();
            UsingEventAggregator<EventAggregator>();
            UsingRegionViewRegistry<RegionViewRegistry>();
            UsingRegionBehaviorFactory<RegionBehaviorFactory>();
            UsingRegionNavigationService<RegionNavigationService>();
            UsingRegionNavigationContentLoader<RegionNavigationContentLoader>();
            UsingRegionNavigationJournal<RegionNavigationJournal>();
            UsingRegionNavigationJournalEntry<RegionNavigationJournalEntry>();
        }

        /// <summary>
        /// Creates the shell using the provided function.
        /// </summary>
        /// <param name="createShell">The create shell function.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration CreateShellUsing(Func<DependencyObject> createShell)
        {
            _createShell = createShell;
            return this;
        }

        /// <summary>
        ///Customizes the logger facade.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingLoggerFacade<T>()
            where T : ILoggerFacade
        {
            _loggerFacade = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the module initializer.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingModuleInitializer<T>()
            where T : IModuleInitializer
        {
            _moduleInitializer = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the module manager.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingModuleManager<T>()
            where T : IModuleManager
        {
            _moduleManager = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the region manager.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionManager<T>()
            where T : IRegionManager
        {
            _regionManager = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the region navigation service.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionNavigationService<T>()
            where T : IRegionNavigationService
        {
            _regionNavigationService = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the region navigation journal.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionNavigationJournal<T>()
            where T : IRegionNavigationJournal
        {
            _regionNavigationJournal = typeof(T);
            return this;
        }
       
        /// <summary>
        /// Customizes the region navigation journal entry.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionNavigationJournalEntry<T>()
            where T : IRegionNavigationJournalEntry
        {
            _regionNavigationJournalEntry = typeof(T);
            return this;
        }
       
        /// <summary>
        /// Customizes the region navigation content loader.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionNavigationContentLoader<T>()
            where T : IRegionNavigationContentLoader
        {
            _regionNavigationContentLoader = typeof(T);
            return this;
        }

        public CompositeApplicationLibraryConfiguration UsingModelRegionManager<T>()
            where T : IModelRegionManager
        {
            _modelRegionManager = typeof(T);
            return this;
        }


        /// <summary>
        /// Customizes the event aggregator.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingEventAggregator<T>()
            where T : IEventAggregator
        {
            _eventAggregator = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the region view registry.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionViewRegistry<T>()
            where T : IRegionViewRegistry
        {
            _regionViewRegistry = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the region behavior factory.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration UsingRegionBehaviorFactory<T>()
            where T : IRegionBehaviorFactory
        {
            _regionBehaviorFactory = typeof(T);
            return this;
        }

        /// <summary>
        /// Customizes the module types.
        /// </summary>
        /// <param name="modules">The modules.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration WithModuleTypes(params Type[] modules)
        {
            _moduleTypes = modules;
            return this;
        }

        /// <summary>
        /// Customizes the module catalog.
        /// </summary>
        /// <param name="moduleCatalog">The module catalog.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration WithModuleCatalog(IModuleCatalog moduleCatalog)
        {
            _moduleCatalog = moduleCatalog;
            return this;
        }

        /// <summary>
        /// Overrides the module initialization.
        /// </summary>
        /// <param name="doThisInstead">The action to perform.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration OverrideModuleInitializationWith(Action doThisInstead)
        {
            _overrideModuleInit = doThisInstead;
            return this;
        }

        /// <summary>
        /// Overrides the region behaviors using the provided action.
        /// </summary>
        /// <param name="doThisInstead">The do this instead.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration OverrideRegionBehaviorsWith(Action<IRegionBehaviorFactory> doThisInstead)
        {
            _overrideRegionBehavior = doThisInstead;
            return this;
        }

        /// <summary>
        /// Executes the action after the region behaviors are configured.
        /// </summary>
        /// <param name="configureBehaviors">The configure behaviors.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration AfterConfigureRegionBehaviors(Action<IRegionBehaviorFactory> configureBehaviors)
        {
            _afterConfigureBehaviors = configureBehaviors;
            return this;
        }

        /// <summary>
        /// Overrides the region adapter mappings using the provided action.
        /// </summary>
        /// <param name="doThisInstead">The do this instead.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration OverrideRegionAdapterMappingsWith(Action<RegionAdapterMappings> doThisInstead)
        {
            _overrideRegionAdapterMappings = doThisInstead;
            return this;
        }

        /// <summary>
        /// Executes the action after configuring the region adapter mappings.
        /// </summary>
        /// <param name="configureRegionAdapterMappings">The configure region adapter mappings.</param>
        /// <returns>.</returns>
        public CompositeApplicationLibraryConfiguration AfterConfigureRegionAdapterMappings(Action<RegionAdapterMappings> configureRegionAdapterMappings)
        {
            _afterConfigureRegionAdapterMappings = configureRegionAdapterMappings;
            return this;
        }

        /// <summary>
        /// Gets the component information for this module.
        /// </summary>
        /// <returns>.</returns>
        public override IEnumerable<IComponentRegistration> GetComponents()
        {
            yield return Singleton(typeof(Microsoft.Practices.ServiceLocation.IServiceLocator), typeof(CommonServiceLocatorAdapter));

            yield return Singleton(typeof(ILoggerFacade), _loggerFacade);
            yield return Singleton(typeof(IModuleInitializer), _moduleInitializer);
            yield return Singleton(typeof(IRegionManager), _regionManager);
            yield return Singleton(typeof(IModelRegionManager), _modelRegionManager);
            yield return Singleton(typeof(IEventAggregator), _eventAggregator);
            yield return Singleton(typeof(IRegionViewRegistry), _regionViewRegistry);
            yield return Singleton(typeof(IRegionBehaviorFactory), _regionBehaviorFactory);
            yield return Singleton(typeof(IRegionNavigationContentLoader), _regionNavigationContentLoader);
            yield return PerRequest(typeof(IRegionNavigationService), _regionNavigationService);
            yield return PerRequest(typeof(IRegionNavigationJournal), _regionNavigationJournal);
            yield return PerRequest(typeof(IRegionNavigationJournalEntry), _regionNavigationJournalEntry);
           
            yield return Singleton(typeof(IModuleManager), _moduleManager);
            yield return Singleton(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings));

            if(_moduleCatalog != null)
                yield return new Instance {Service = typeof(IModuleCatalog), Implementation = _moduleCatalog  };
   
            if(_moduleTypes != null)
            {
                foreach (var module in _moduleTypes)
                {
                    yield return Singleton(module, module);
                }
            }
           
            /* Patch to support Containers that require explicit Component registration */
            //register default adapters
            yield return PerRequest(typeof(SelectorRegionAdapter), typeof(SelectorRegionAdapter));
            yield return PerRequest(typeof(ItemsControlRegionAdapter), typeof(ItemsControlRegionAdapter));
            yield return PerRequest(typeof(ContentControlRegionAdapter), typeof(ContentControlRegionAdapter));
#if SILVERLIGHT
            yield return PerRequest(typeof(TabControlRegionAdapter), typeof(TabControlRegionAdapter));
#endif

            //register default behaviors
            yield return PerRequest(typeof(AutoPopulateRegionBehavior), typeof(AutoPopulateRegionBehavior));
            yield return PerRequest(typeof(BindRegionContextToDependencyObjectBehavior), typeof(BindRegionContextToDependencyObjectBehavior));
            yield return PerRequest(typeof(RegionActiveAwareBehavior), typeof(RegionActiveAwareBehavior));
            yield return PerRequest(typeof(SyncRegionContextWithHostBehavior), typeof(SyncRegionContextWithHostBehavior));
            yield return PerRequest(typeof(RegionManagerRegistrationBehavior), typeof(RegionManagerRegistrationBehavior));
            yield return PerRequest(typeof(DelayedRegionCreationBehavior), typeof(DelayedRegionCreationBehavior));
        }
 
        /// <summary>
        /// Initializes this module.
        /// </summary>
        public override void Initialize(Caliburn.Core.InversionOfControl.IServiceLocator serviceLocator)
        {
            base.Initialize(serviceLocator);

            ConfigureRegionAdapterMappings();
            ConfigureRegionBehaviors();
            RegisterFrameworkExceptionTypes();

            CaliburnModule<CoreConfiguration>.Instance.AfterStart(CreateShell);

            // Initialize modules after caliburn has started in order for the DefaultBinder
            // conventions to work
            CaliburnModule<CoreConfiguration>.Instance.AfterStart(InitializeModules);
        }

        private void CreateShell()
        {
            var shell = _createShell();
            if(shell == null)
                return;

            RegionManager.SetRegionManager(
                shell,
                ServiceLocator.Current.GetInstance<IRegionManager>()
                );

            RegionManager.UpdateRegions();
        }

        private void InitializeModules()
        {
            if(_overrideModuleInit != null)
            {
                _overrideModuleInit();
                return;
            }

            if (_moduleCatalog == null && _moduleTypes == null)
                throw new InvalidOperationException(
                    string.Format(
                        "{0} {1}",
                        "Failed to initialize modules.",
                        "You must provide modules to load through either the WithModules or WithModuleCatalog methods")
                    );

            if(_moduleTypes != null)
                _moduleTypes.Apply(x =>{
                    var module = ServiceLocator.Current.GetInstance(x) as IModule;
                    if (module != null)
                    {
                        AddAssemblyIfMissing(x.Assembly);
                        module.Initialize();
                    }
                });

            if(_moduleCatalog == null)
                return;
 
            var manager = ServiceLocator.Current.TryResolve<IModuleManager>();
            if (manager != null)
                manager.Run();
        }

        private void AddAssemblyIfMissing(Assembly assembly)
        {
            var assemblySource =  ServiceLocator.Current.TryResolve<IAssemblySource>();
            if(assemblySource != null)
                if (!assemblySource.Contains(assembly))
                    assemblySource.Add(assembly);
        }

        private void ConfigureRegionAdapterMappings()
        {
            var regionAdapterMappings = ServiceLocator.Current.TryResolve<RegionAdapterMappings>();
            if (regionAdapterMappings == null)
                return;

            if(_overrideRegionAdapterMappings != null)
            {
                _overrideRegionAdapterMappings(regionAdapterMappings);
                return;
               
            }

#if SILVERLIGHT
            regionAdapterMappings.RegisterMapping(
                typeof(TabControl),
                ServiceLocator.Current.GetInstance<TabControlRegionAdapter>()
                );
#endif
            regionAdapterMappings.RegisterMapping(
                typeof(Selector),
                ServiceLocator.Current.GetInstance<SelectorRegionAdapter>()
                );

            regionAdapterMappings.RegisterMapping(
                typeof(ItemsControl),
                ServiceLocator.Current.GetInstance<ItemsControlRegionAdapter>()
                );

            regionAdapterMappings.RegisterMapping(
                typeof(ContentControl),
                ServiceLocator.Current.GetInstance<ContentControlRegionAdapter>()
                );

            if(_afterConfigureRegionAdapterMappings != null)
                _afterConfigureRegionAdapterMappings(regionAdapterMappings);
        }

        private void ConfigureRegionBehaviors()
        {
            var defaultRegionBehaviorTypesDictionary = ServiceLocator.Current.TryResolve<IRegionBehaviorFactory>();

            if(defaultRegionBehaviorTypesDictionary == null)
                return;


            if (_overrideRegionBehavior != null)
            {
                _overrideRegionBehavior(defaultRegionBehaviorTypesDictionary);
                return;
            }

            defaultRegionBehaviorTypesDictionary.AddIfMissing(
                AutoPopulateRegionBehavior.BehaviorKey,
                typeof(AutoPopulateRegionBehavior)
                );

            defaultRegionBehaviorTypesDictionary.AddIfMissing(
                BindRegionContextToDependencyObjectBehavior.BehaviorKey,
                typeof(BindRegionContextToDependencyObjectBehavior)
                );

            defaultRegionBehaviorTypesDictionary.AddIfMissing(
                RegionActiveAwareBehavior.BehaviorKey,
                typeof(RegionActiveAwareBehavior)
                );

            defaultRegionBehaviorTypesDictionary.AddIfMissing(
                SyncRegionContextWithHostBehavior.BehaviorKey,
                typeof(SyncRegionContextWithHostBehavior)
                );

            defaultRegionBehaviorTypesDictionary.AddIfMissing(
                RegionManagerRegistrationBehavior.BehaviorKey,
                typeof(RegionManagerRegistrationBehavior)
                );

            if(_afterConfigureBehaviors != null)
                _afterConfigureBehaviors(defaultRegionBehaviorTypesDictionary);
        }

        /// <summary>
        /// Registers in the <see cref="ServiceLocator"/> the <see cref="Type"/> of the Exceptions
        /// that are not considered root exceptions by the <see cref="ExceptionExtensions"/>.
        /// </summary>
        private void RegisterFrameworkExceptionTypes()
        {
            ExceptionExtensions.RegisterFrameworkExceptionType(
                typeof(ActivationException)
                );
        }
    }
}

Feb 23, 2011 at 12:40 AM

The issue was resolved by adding a delay before the Caliburn.Configure() call.

Jul 25, 2011 at 11:19 AM

We too have experienced a very similar problem. It seems to be more likely to occur when the machine is under heavy load. Is this some kind of race condition?

 

'NavigationRegion' value cannot be assigned to property 'RegionName' of object 'System.Windows.Controls.ContentControl'. Resolution of the dependency failed, type = "Microsoft.Practices.ServiceLocation.IServiceLocator", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?

-----------------------------------------------

At the time of the exception, the container was:

 

Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)

Error at object 'System.Windows.Controls.ContentControl' in markup file 'Project;component/shell.xaml' Line 128 Position 83.

 

-------- Stack Trace ------------

   at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)

   at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)

   at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)

   at System.Windows.Markup.BamlRecordReader.ReadPropertyRecordBase(String attribValue, Int16 attributeId, Int16 converterTypeId)

   at System.Windows.Markup.BamlRecordReader.ReadPropertyConverterRecord(BamlPropertyWithConverterRecord bamlPropertyRecord)

   at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)

   at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)

   at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()

   at System.Windows.Markup.TreeBuilder.Parse()

   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)

   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)

   at Company.Project.Shell.Shell.InitializeComponent() in c:\Users\chris.wood\Desktop\Project Front End\ProjectShell\Shell.xaml:line 1

   at Company.Project.Shell.Shell..ctor() in C:\Users\chris.wood\Desktop\Project Front End\ProjectShell\Shell.xaml.cs:line 33

   at BuildUp_Company.Project.Shell.Shell(IBuilderContext )

   at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)

   at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)

   at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)

 

------------ Inner Exception ------------

 

Resolution of the dependency failed, type = "Microsoft.Practices.ServiceLocation.IServiceLocator", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?

-----------------------------------------------

At the time of the exception, the container was:

 

Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)

 

------------ Stack Trace ----------------

   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)

   at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)

   at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)

   at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)

   at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.<ConfigureContainer>b__0()

   at Microsoft.Practices.ServiceLocation.ServiceLocator.get_Current()

   at Microsoft.Practices.Composite.Presentation.Regions.RegionManager.CreateRegion(DependencyObject element)

   at Microsoft.Practices.Composite.Presentation.Regions.RegionManager.OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)

   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)

   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)

   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)

   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)

   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal)

   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)

   at System.Windows.Markup.BamlRecordReader.SetDependencyValueCore(DependencyObject dependencyObject, DependencyProperty dependencyProperty, Object value)

   at System.Windows.Markup.BamlRecordReader.SetDependencyValue(DependencyObject dependencyObject, DependencyProperty dependencyProperty, Object value)

   at System.Windows.Markup.BamlRecordReader.SetPropertyValue(Object o, PropertyDefinition propertyDefinition, Object value)

   at System.Windows.Markup.BamlRecordReader.ReadPropertyRecordBase(String attribValue, Int16 attributeId, Int16 converterTypeId)

Mar 26, 2012 at 10:00 AM

Hello guys,

Im in the same situation:

My problem comes after initialize the application, when I try to perform a RequestNavigate to the IRegionManager of Prism. The excepction and stacktrace is the same, can not resolve iServiceLocator interface.
This occurs sometimes without any special change in the source code: sometimes occurs sometimes not occurs.
I use the Unitybootstrapper to initialize the application only overriding the CreateModuleCatalog and CreateContainer methods.
Has somebody discovered any way to solve the problem and the "true source" of that?

I'm desperate I don't know how to proceed!

Thanks in advance

Mar 26, 2012 at 11:17 AM

In the end I found that in my case this was being caused when the app.config file was being modified. We were using ConfigurationManager.OpenExeConfiguration to save settings to the app.config file directly (I know) instead of using the user settings. As soon as this was fixed the problem disappeared.

Mar 26, 2012 at 3:43 PM

Hi chrisdotwood7,

Your suggestion has solved my problem. Thank you very very very very very much for your lines!!!!!

But........ I need change the app.config in runtime by using ConfigurationManager.OpenExeConfiguration, because Im using LogginConfiguration of EnterpriseLibrary and some values (for example log filename) must be changed in runtime with the localUser name and machine name, and I think that only is possible by opening the app.config.

Otherwise, do you know other way to change app.config values without use ConfigurationManager.OpenExeConfiguration?

Other time, thank you vey very much.