ViewModel with dependencies on Services + tombstoning

156 views Asked by At

What is the recommended way to set up / inject dependencies in a viewModel after tombstoning given that when the app deactivates you typically add the ViewModel to the State dictionary and then before your app reactivates the framework deserialises the ViewModel which requires a default constructor?

If I have the class below, I would like to have dependency injection create an instance of "MyVM" injecting the dependencies for IServiceA and IServiceB. Having a default constructor would not set up the requried dependecies.

public class MyVM(IServiceA svca,IServiceB svcB)
{

}

How should the ViewModel be setup in a tombstoning scenario here?

1

There are 1 answers

0
Derek Beattie On

I don't know if you're using a specific MVVM framework but Caliburn Micro has some built in features for tombstoning.

A little snippet from the docs:

public class PivotPageModelStorage : StorageHandler<PivotPageViewModel> {  
    public override void Configure() {  
        this.ActiveItemIndex()  
            .InPhoneState()  
            .RestoreAfterViewLoad();  
    }  
}  

That example is storing the ActiveItemIndex, a property on PiveotPageViewModel, in phone state but it can also store entire object graphs in PhoneState, AppSettings, or your own custom implementation. You get all that by inheriting from StorageHandler. With CM you don't have to worry about re-injecting services, it will handle that for you as it has it's own built in container.

CM WP7 Docs

In a recent Hanselman post about building a WP7 app he talked a bit about TombstoneHelper. I haven't used this one but it looks interesting.