Prism for Windows Runtime: Integrating a Dependency Injection Container

This is the fourth post in a series that walk you through creating a simple Windows Store app using the Prism for Windows Runtime library. Please review the third post in the series for the steps necessary to create the basic MVVM style app based on MvvmAppBase.

You can get the latest source on CodePlex.

The following procedure shows how to integrate a dependency injection container into a Windows Store app that leverages MvvmAppBase from the Microsoft.Practices.Prism.StoreApps library.

  1. Add a reference to a Dependency Injection Container library. This walk through will use the Unity v3 container which is available via nugget (https://www.nuget.org/packages/Unity/).

  2. Add a private member varliable to the App class that will hold the container.

     private UnityContainer _container = new UnityContainer();
    
  3. Override the Resolve method on the App class so that it uses the container to resolve object instances from a type.

     protected override object Resolve(Type type)
    {
        return _container.Resolve(type);
    }
    
  4. You can now remove the call to ViewModelLocator.Register in App.OnInitialize because the ViewModelLocator can use the container to resolve view model types. Register into the container any services that will need to be provided to view models via constructor injection. The StartPageViewModel needs an instance of IFlyoutService. The following code registers the three services provided by the MvvmAppBase.

     protected override void OnInitialize(IActivatedEventArgs args)
    {
        _container.RegisterInstance(NavigationService);
        _container.RegisterInstance(FlyoutService);
        _container.RegisterInstance(SessionStateService);
    }
    
  5. Run the app. Notice that the button still causes the FlyoutService to show the SignInFlyout.