In my universal app I have a MainViewModel that I share between both the windows and the Phone projects. Depending on what project is run, I would like the MainViewModel to implement a different interface. Lets say these are my two classes and the interface that they both implements:
public class PhotoPhone : IPhotograph
{
//some methods
}
public class PhotoWin : IPhotograph
{
//some methods
}
public interface IPhotograph
{
//some signatures
}
And here is my MainViewModel:
public class MainViewModel : ViewModelBase
{
private IPhotograph _phot;
public MainViewModel(IPhotograph photo)
{
// Depending on what platform is running
//I want the proper implementation
}
}
But how can I make my MainViewModel implement the correct implementation of IPhotograph? I'm thinking that maybe some code should be added to my App.Xaml file. Is this maybe the wrong way to go about this issue? I would like to learn the proper way by following MVVM as far as possible.
Two words: dependency injection. Basically, you want your view model to be as ignorant of the details of phone or desktop/laptop or web environment as the rest of the code, so you need to have a different component handling which implementation of
IPhotograph
is actually instantiated. This component is called the dependency injector; there are a lot of frameworks in .NET for this, like StructureMap, Spring.NET, Ninject, Autofac, Unity, Castle Windsor, and so forth.In Unity, you'd probably set up a pair of configuration files, one for phone and one for Windows, and register types in those, and in particular register different implementations of
IPhotograph
in each. Then make sure the only part of your application that knows about Unity or any concrete types is the initialization point. Seems like you've already gotten that mostly done, using interfaces for most things.