MVVM

Using ViewModelLocator and UnityContainer to resolve runtime and design time ViewModel instance

We can use a ViewModel locator class to resolve runtime and design time data. Again, we need to identify if it’s in design mode or not, if it’s in design mode, we add the mock extension if not, we add the actual extension.

public class ViewModelLocator
{
	UnityContainer Container;

	public ViewModelLocator()
	{
		this.container = new UnityContainer();

		if(this.IsInDesignMode)
			this.Container.AddNewExtension<MockContainerExtension>();
		else
			this.Container.AddNewExtension<MyAppContainerExtension>();
	}

	public MainPageViewModel Main
	{
		get
		{
			return this.Container.Resolve<MainPageViewModel>();
		}
	}
}

Now we want to create a UnityContainerExtension. We use the extension for us to be able to create a separate class that will initialize the design time instance and the runtime instance. You will notice that inside the MockContainerExtension’s Initialize method, instead of using RegisterType, I used RegisterInstance to provide a test data to the container. This test data will show up in the designer.

public class MockContainerExtension : UnityContainerExtension
{
	protected override void Initialize()
	{
		var mainPageViewModel = new MainPageViewModel();
		mainPageViewModel.Title = "This is my mainpage test data";
		this.Container.RegisterInstance<MainPageViewModel>(mainPageViewModel);
	}
}

public class MyAppContainerExtension : UnityContainerExtension
{
	protected override void Initialize()
	{
		this.Container.RegisterType<IDataService, SomeDataService>();
		this.Container.RegisterType<MainPageViewModel>();
	}
}

Here we can see how we create an instance of the ViewModelLocator class in the App.xaml.

<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyApp" RequestedTheme="Dark">
	<Application.Resources>
		<local:ViewModelLocator x:Key="ViewModelLocator" />
	</Application.Resources>
</Application>

To use the ViewModelLocator in our page we simply put it in the source of the binding and the binding path should be the property Main that should give us the MainPageViewModel.

<Page x:Class="MyApp.Views.MainPage" DataContext="{Binding Main, Source={StaticResource ViewModelLocator}}">
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s