Bogdan Bujdea

Windows Platform Developer

Daily tip #1: Caliburn.Micro IoC is not initialized

It’s been more than half a year since I made this blog and I haven’t made more than 10 posts, so I thought that I should start writing all kinds of stuff that I want to share with other people. For example, I’ll start a series of short posts about problems that I had and what I had to do to solve them.

I recently launched my app, DriveKit(Windows Phone only), and I had a problem with voice commands. I should also mention that the app is for Windows Phone 8.1(not Silverlight). I’m using Caliburn.Micro for MVVVM and the problem was that the Caliburn was not initialized when the app was activated with voice commands. If the app was already open when I gave it a voice command, it worked fine, but if it was completely closed, it wasn’t working. I made a post on StackOverflow but I hadn’t receive any answer so I decided to start digging in Caliburn and try to fix the problem.

Here’s how my code looked before:

protected override async void OnActivated(IActivatedEventArgs args)
{
  if ( args.Kind == ActivationKind.VoiceCommand )
  {
    var service = IoC.Get(); //IService doesn't exist, it's just an example
    RootFrame.Navigate(typeof(MyView)); //I'm not actually using RootFrame directly to navigate, I'm just using this to point out that RootFrame is null so you can't use it to navigate
  }
}

When I tried to get an instance of the IService, I would receive an error saying that IoC is not initialized, so I had to manually initialize it. After many trials and errors, I came to this solution:

protected override async void OnActivated(IActivatedEventArgs args)
{
  if ( args.Kind == ActivationKind.VoiceCommand )
  {
                Initialize();
                PrepareApplication();
                PrepareViewFirst();
                var service = IoC.Get<IService>();
                DisplayRootView(typeof(MyView));
  }
}

I have a wrapper for INavigationService from Caliburn which I’m using to navigate between pages but if I’ll use it here, it will just start the view model and it won’t display the view. That’s why here you have to use the DisplayRootView function, and after that you can go back to using INavigationService.

 

, , ,