Some Gotchas with the new WP7 Stuff

Aug 10, 2010 at 2:41 AM

I just spent a bit struggling to figure out why the sample from the latest Soup to Nuts WP7 post works fine when using the SimpleContainer but stopped working when I tried to replace the IOC. I finally narrowed it down to this line in the boostrapper's Configure method:

container.RegisterInstance(typeof(INavigationService), null, new FrameAdapter(RootFrame));  

The problem was I was also registering the INavigationService in my IOC as well but the FrameAdapter was not created at registration time like this. This caused my ViewModels to not be instantiated when a page was navigated to. I believe this has to do with the fact that all of the event wiring for navigation is done in the constructor of the FrameAdapter class.

Another gotcha is that the ViewModels are sent to your IOC container as string keys and not as types. This works fine with the SimpleContainer recipe but if you are working with an IOC container which requires types this is a problem. I worked around this by doing something like:

protected override object GetInstance(Type service, string key)
	if (service == null && !String.IsNullOrEmpty(key))
		service = Type.GetType("MyViewModelNamespace." + key);

	return MyContainer.Get(service);

I was able to work past both of these gotchas but I thought I would mention them here in case anybody else runs into them.

Aug 10, 2010 at 3:28 AM
I'm not sure I understand the first gotcha. About the second, another way to change this is to replace methods of the ViewModelLocator so that they resolve from the container by type rather than by key.
Aug 10, 2010 at 4:46 AM

The first gotcha has to do with whether or not the FrameAdapter is instantiated at registration time or at some later time by the IOC container. If the instantiation is left until some time later then the navigation events inside the FrameAdapter constructor are not wired up in time and it seems to cause the ViewModels to not be instantiated and bound to the Views when navigation occurs.