Caliburn.Micro DisplayRootViewFor抛出NullReferenceException
我的Bootstrapper中有以下代码:
private SimpleContainer container; protected override void Configure() { container = new SimpleContainer(); container.Singleton(); container.PerRequest(); } protected override object GetInstance(Type service, string key) { return container.GetInstance(service, key); } protected override IEnumerable GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override void BuildUp(object instance) { container.BuildUp(instance); }
在OnStartup方法中,我调用DisplayRooViewFor
方法:
protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor(); }
这是InitialViewModel:
private IEventAggregator eventAggregator; public InitialViewModel(IEventAggregator ea) { eventAggregator = ea; }
不幸的是,它抛出了NullReferenceException :
Caliburn.Micro.Platform.dll中出现“System.NullReferenceException”类型的exception,但未在用户代码中处理
我检查了CM的源代码并使用相同的代码来测试它:
protected override void OnStartup(object sender, StartupEventArgs e) { var viewModel = IoC.GetInstance(typeof(InitialViewModel), null); var view = ViewLocator.LocateForModel(viewModel, null, null); ViewModelBinder.Bind(viewModel, view, null); var activator = viewModel as IActivate; if (activator != null) activator.Activate(); DisplayRootViewFor(); }
奇怪的是,这些方面没有例外。 view和viewmodel都有引用,并且调用了InitialView的构造函数,但是当它到达并调用DisplayRootViewFor
,它仍然会引发exception。
我应该改变什么?
我的容器缺少关键组件:
container.Singleton();
你在SimpleContainer和MEF注入之间混合。 你应该只使用其中一个。
MEF :如果你的InitialViewModel应该使用MEF进行构造函数注入,你必须创建一个Bootstrapper来处理它,就像在这篇文章中一样 。 请记住导出InitialViewModel并删除SimpleContainer代码。
SimpleContainer或者您删除MEF(通过简单地删除ImportingConstructor-Attribute),SimpleContainer将获取Job。
您的InitialViewModel应该inheritanceCaliburn.Micro Screen类,如果它附加了主窗口。
初始化(); 需要在Bootstrapper CTOR中调用方法。