【发布时间】:2014-06-12 02:38:03
【问题描述】:
我的应用程序是一个 IDE 插件,因此该项目是一个 wpf 用户控件。我现在想用棱镜来反射它。当我调试应用程序时,它在MainView 的构造函数的InitializeComponent(); 中抛出了这样的异常:
"ServiceLocationProvider must be set."
我在这里也找到了一个类似的帖子:Strange exception in Prism application 但没有解决办法。
这是我的引导类:
class Bootstrapper : UnityBootstrapper
{
protected override System.Windows.DependencyObject CreateShell()
{
return ServiceLocator.Current.GetInstance<MainView>();
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog catalog = (ModuleCatalog)this.ModuleCatalog;
catalog.AddModule(typeof(ModuleInit));
}
}
这是我的 ModuleInit 类:
public class ModuleInit : IModule
{
IRegionManager regionManager;
IUnityContainer container;
public ModuleInit(IUnityContainer container, IRegionManager regionManager)
{
this.container = container;
this.regionManager = regionManager;
}
public void Initialize()
{
this.container.RegisterType<ViewModelA>(new ContainerControlledLifetimeManager());
this.container.RegisterType<MainViewModel>(new ContainerControlledLifetimeManager());
this.regionManager.RegisterViewWithRegion(Models.RegionNames.ARegion, () => this.container.Resolve<ViewModelA>());
}
}
因为这是一个用户控件项目,所以没有 App.xaml 和 App.xaml.cs 文件。我可以在 MainView 的构造函数中引导运行方法:
public MainView()
{
InitializeComponent();
Bootstrapper strapper = new Bootstrapper();
strapper.Run();
}
但是在构造函数的第一行就抛出了异常。有人可以帮忙吗?
此外,有没有办法在没有模块化的情况下使用 Region?我的应用程序只包含一个项目,它不需要模块化。如果是,我在哪里可以注册视图、服务和视图模型?
【问题讨论】:
-
为什么要使用服务定位器来查找shell的实例?为什么没有统一的决心呢?
-
@GayotFow 使用这段代码有同样的问题:protected override System.Windows.DependencyObject CreateShell() { return this.Container.TryResolve
(); } -
这是要解决的问题。如果团结做不到,那就大错特错了。因为容器抛出异常而使用服务管理器只是隐藏了问题。
-
我现在看到了问题。您正在尝试从构造函数中运行引导程序。初始化组件被调用了两次,因为主视图从未被构造。
-
@GayotFow 我应该在哪里调用 run 方法?我的项目中没有 App.xaml 和 App.xaml.cs 文件