简体   繁体   中英

How solve circular reference in Caliburn.Micro

I am working with Caliburn.Micro v2.0.1 on a Windows 8.1 Unversal (WinRT) project.

I followed the Caliburn.Micro Working with WinRT example.

My code looks as follows:

App.xaml.cs

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    Initialize();
    DisplayRootViewFor<LoginViewModel>();
}

protected override void PrepareViewFirst(Frame rootFrame)
{
    _container.RegisterNavigationService(rootFrame);
}

LoginViewModel.cs

public LoginViewModel(INavigationService navigationService, ...)
{
   ...
}

The issue

The OnLaunched is called first.

Initialize() Configures the WinRT container.

  1. The DisplayRootViewFor<LoginViewModel> invokes an instance of the LoginViewModel and results in a Null exception because NavigationService has not yet been registered by PrepareViewFirst(Frame)
  2. PrepareViewFirst(Frame) is not yet called, having a dependency on the RootFrame that should be configured by OnLaunched

Thus LoginViewModel is dependent on RegisterNavigationService and RegisterNavigationService is dependent on DisplayRootViewFor<LoginViewModel>() which is dependent on LoginViewModel

Is there any way to overcome this circular reference issue?

Register your services in the container before resolving the Views - this way all dependencies are available in the particular Dependency Injection container and you can use ServiceLocator to find them.

Typically I've always done this in the OnStartup() method of App.xaml.cs .

You should register/configure your container at the composition root , the earliest access point of your application.

This point depends on what kind of Application you have:

etc.

Check the Windows 7 lifecycle on http://msdn.microsoft.com/en-us/magazine/hh148153.aspx 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM