What i have
Using MVVMLight, I have some service interfaces declared in a portable project and corresponding implementations in a Windows Phone project (WP8.1 SL). To register implementations, I use SimpleIoc.Default.Register in the Application_Launching method in the App class.
public partial class App : Application { ... private async void Application_Launching(object sender, LaunchingEventArgs e) { ...
The view model locator is in the portable project and registers all view models in the IOC container in the static constructor, as the docs say.
static ViewModelLocator() { ... SimpleIoc.Default.Register<TagColorViewModel>(); ... }
TagColorViewModel is one of these models. It receives a message before displaying the corresponding view. For example, when you click a tag to change its color, MessengerInstance.Send used, and then the navigation service is used to go to the type of color change of the tag.
// TagViewModel private void ChangeColor() { MessengerInstance.Send(Tag, TagColorViewModel.MessengerToken.SetTag); _navigationService.Navigate("/UI/Tagging/TagColor.xaml"); }
This message receiver is registered in the constructor.
// TagColorViewModel [PreferredConstructor] public TagColorViewModel(INavigationService navigationService) { ... // Messages MessengerInstance.Register<Tag>(this, MessengerToken.SetTag, SetTag); }
Actual problem
Since the view model is created in MVVMLight just before its first use through the corresponding view, the message is not accepted by TagColorViewModel (simply because there is no instance of this virtual machine yet).
A possible solution would be to use true as a parameter when registering the view model.
SimpleIoc.Default.Register<TagColorViewModel>(true);
This, unfortunately, does not work. The reason is that, as can be seen from the above constructor, TagColorViewModel has a dependency on INavigationService . This, in turn, is registered in the Application_Launching method, which after calling the static constructor of the view model locator. As a result, SimpleIoc cannot create an instance of TagColorViewModel because there is no known INavigationService interface or implementation.
Actual question
How can I solve this problem? In other words: How can I register certain platforms in MVVMLights SimpleIoc so that I can let it instantiate view models while they are registered?
Xamarin seems to be using a decorator to solve such problems, but I don't know any comparable construct in MVVMLight.
Xamarin.Forms.Dependency(typeof(PopupService))
Current workaround
My current workaround is to get an instance that is never used later right after registering all the platform-specific services. It works, but I do not think this is the right solution.
private async void Application_Launching(object sender, LaunchingEventArgs e) { ...