Caliburn.Micro DisplayRootViewFor throws NullReferenceException

此生再无相见时 提交于 2020-01-03 12:25:05

问题


I have the following code in my Bootstrapper:

private SimpleContainer container;

protected override void Configure()
{
  container = new SimpleContainer();
  container.Singleton<IEventAggregator, EventAggregator>();
  container.PerRequest<InitialViewModel>();  
}

protected override object GetInstance(Type service, string key)
{
  return container.GetInstance(service, key);
}

protected override IEnumerable<object> GetAllInstances(Type service)
{
  return container.GetAllInstances(service);
}

protected override void BuildUp(object instance)
{
  container.BuildUp(instance);
}

In the OnStartup method, I call the DisplayRooViewFor method:

protected override void OnStartup(object sender, StartupEventArgs e)
{ 
  DisplayRootViewFor<InitialViewModel>();
}

This is the InitialViewModel:

    private IEventAggregator eventAggregator;    

    public InitialViewModel(IEventAggregator ea) 
    {
      eventAggregator = ea;
    }

Unfortunately, it throws a NullReferenceException:

An exception of type 'System.NullReferenceException' occurred in Caliburn.Micro.Platform.dll but was not handled in user code

I checked the source code of CM and used the same code to test it:

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

Strangely, there was no Exception at those lines. Both view and viewmodel have reference, and the constructor of InitialView gets called, but when it reaches and calls DisplayRootViewFor, it still throws an exception.

What should I change?


回答1:


My container was missing a critical component:

container.Singleton<IWindowManager, WindowManager>();



回答2:


You're mixing between SimpleContainer and MEF injection. You should only use one of them.

MEF: If your InitialViewModel should use MEF for constructor injection, you have to create a Bootstrapper to deal with it, like in this post. Remember to Export your InitialViewModel and remove SimpleContainer Code.

SimpleContainer Or you remove MEF (by simply removing ImportingConstructor-Attribute), the SimpleContainer will take the Job.

Your InitialViewModel should inherit Caliburn.Micro Screen class if it's attached with main window.




回答3:


Initialize(); method needs to be called in your Bootstrapper CTOR.



来源:https://stackoverflow.com/questions/35721047/caliburn-micro-displayrootviewfor-throws-nullreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!