System.InvalidOperationException:必须在 Prism ConfigureContainer() 中设置 ServiceLocationProvider

System.InvalidOperationException: ServiceLocationProvider must be set in Prism ConfigureContainer()

我是 Prism 的新手,正在学习 Brian Lagunas 的教程 Introduction to prism,并且正在创建如下所示的自定义 regionAdapter。

public class StackPanelRegionAdapter : RegionAdapterBase<StackPanel>
{
    public StackPanelRegionAdapter(IRegionBehaviorFactory regionBehavior )
        :base(regionBehavior)
    {

    }
    protected override void Adapt(IRegion region, StackPanel regionTarget)
    {
        region.Views.CollectionChanged += (s, e) =>
           {
               if(e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
               {
                   foreach(FrameworkElement frameworkElement in e.NewItems)
                   {
                       regionTarget.Children.Add(frameworkElement);
                   }
               }
           };
    }

    protected override IRegion CreateRegion()
    {
        return new AllActiveRegion();
    }
}

在引导程序中

protected override void ConfigureContainer()
{
     RegionAdapterMappings regionAdapterMappings = base.ConfigureRegionAdapterMappings();

     regionAdapterMappings.RegisterMapping(typeof(StackPanel), 
            Container.Resolve<StackPanelRegionAdapter>());
}

我遇到异常

System.InvalidOperationException: ServiceLocationProvider must be set

在这里

RegionAdapterMappings regionAdapterMappings = base.ConfigureRegionAdapterMappings();

我做错了什么?

您应该在 ConfigureRegionAdapterMappings 的覆盖中配置您的区域适配器映射,而不是伪装成 ConfigureContainer 的覆盖。

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
    var regionAdapterMappings = base.ConfigureRegionAdapterMappings();
    regionAdapterMappings.RegisterMapping(typeof(StackPanel), ServiceLocator.Current.GetInstance<StackPanelRegionAdapter>());
    return regionAdapterMappings;
} 

提示:你会得到异常,因为 ConfigureContainerConfigureServiceLocator 之前被调用,而 base.ConfigureRegionAdapterMappings 使用 ServiceLocator.Current.